Link: http://pat.zju.edu.cn/contests/ds/3-07
Arithmetic expressions include prefix, infix, and suffix. Prefix expression indicates that a binary operator is located before two arithmetic operations. For example, the prefix expression of 2 + 3 * (7-4) + 8/4 is ++ 2*3-7 4/8 4. Please design a program to calculate the result value of the prefix expression.
Input format description:
Enter a prefix expression of no more than 30 characters in a row, including only the +,-, *, \, and number of operations. Different objects (Operation Number and operator number) are separated by spaces.
Output format description:
Output the operation result of the prefix expression, accurate to the first digit after the decimal point, or the error message "error ".
Sample input and output:
Serial number |
Input |
Output |
1 |
+ + 2 * 3 - 7 4 / 8 4 |
13.0 |
2 |
/ -25 + * - 2 3 4 / 8 4 |
12.5 |
3 |
/ 5 + * - 2 3 4 / 8 2 |
ERROR |
4 |
+10.23 |
10.2 |
The Code is as follows:
# Include <cstdio> # include <cstring> # include <iostream> # include <algorithm> # include <stack> using namespace STD; char s [47]; stack <double> SS; int is_op (char C) {If (C = '+' | C = '-' | C = '*' | C = '/') return 1; return 0;} int main () {While (gets (s) {While (! SS. empty () // clear {ss. pop () ;}int Len = strlen (s); int cc = 1; double tsum = 0; int flag = 0; // mark whether zero is used as the divisor for (INT I = len-1; I> = 0; I --) {If (s [I]> = '0' & S [I] <= '9') {tsum + = (s [I]-'0 ') * cc; CC * = 10;} else if (s [I] = '. ') // fractional {tsum = tsum/(CC * 1.0); CC = 1 ;} else if (S [I] = '+' | s [I] = '-') & tsum! = 0) {If (s [I] = '+') {ss. push (tsum); I --; // skip the next space continue;} else {tsum =-tsum; SS. push (tsum); I --; // skip the next space continue;} else if (s [I] = '') // One of the operations has been counted {ss. push (tsum); tsum = 0; CC = 1; continue;} else if (is_op (s [I]) // if the operator is {double A = ss. top (); SS. pop (); Double B = ss. top (); SS. pop (); double TT = 0; If (s [I] = '+') TT = a + B; else if (s [I] = '-') tt = A-B; else if (s [I] = '*') TT = a * B; else if (s [I] = '/') {If (B = 0) {Flag = 1; break;} TT = A/B;} ss. push (TT); I --; // skip the next space}/* int K = 0; // record the number of remaining digits in the last stack, if there are more than one, errorint Lenn = ss. size (); double tt; For (INT I = 0; I <Lenn; I ++) {TT = ss. top (); SS. pop (); If (! Is_op (TT) {k ++ ;}} if (flag! = 1) printf ("%. 1lf \ n", TT); */If (flag! = 1) printf ("%. 1lf \ n", ss. Top (); elseprintf ("error \ n");} return 0 ;}
3-07. Evaluate the prefix expression value (25) (zju_pat mathematics)