Expression evaluation time limit: theMs | Memory Limit:65535KB Difficulty:4
-
-
Describe
-
The ACM team's MDD wants to make a calculator, but what he's going to do is not just a calculator that calculates a a+b, he wants to implement the calculators that can find its value by typing in an expression, now please help him to implement the calculator.
For example, input: "1+2/4=", the program will output 1.50 (results reserved two decimal places)
-
-
Input
-
-
the first line enters an integer n, and there are n sets of test data (N<10).
Each set of test data has only one row, which is a string of not more than 1000 in length, representing the formula, each of which ends with a "=". This expression contains only +-*/and parentheses. Where parentheses can be used in a nested set. The data guarantees that no negative numbers appear in the operands entered.
Data guarantee Divisor is not 0
-
-
Output
-
-
each group outputs the result of the operation of the group, and the output retains two decimal places.
-
-
Sample input
-
-
21.000+2/4= ((1+2) *5+1)/4=
-
-
Sample output
-
-
1.504.00
-
-
Code:
-
#include <stdio.h>double fun (double a,double B,char ch) {if (ch== ' + ')return b+a;if (ch== '-')return b-a;if (ch== ' * ')return b*a;if (ch== '/')return b/a;} int main (void) {int i,top1,top2;int n;Double x,t,a,b;Double num[1000];Char str[1000],ch[1000];scanf ("%d", &n);while (n--){scanf ("%s", str);Top1=-1;Top2=-1;for (i=0;str[i]!= ' n '; i++){x=0;if (str[i]>= ' 0 ' &&str[i]<= ' 9 '){while (str[i]>= ' 0 ' &&str[i]<= ' 9 '){x=x*10+str[i]-' 0 ';i++;}if (str[i]== '. '){i++;t=0.1;while (str[i]>= ' 0 ' &&str[i]<= ' 9 '){x=x+ (str[i]-' 0 ') *t;t=t*0.1;i++;}}top1++;Num[top1]=x;}if (str[i]== ')Breakelse if (str[i]== ' ('){Ch[++top2]=str[i];}else if (str[i]== ') '){while (top2>=0&&ch[top2]!= ' ('){A=NUM[TOP1];top1--;B=NUM[TOP1];Num[top1]=fun (A,b,ch[top2]);top2--;}top2--;}else if (str[i]== ' * ' | | str[i]== '/'){while (ch[top2]== ' * ' | | ch[top2]== '/'){A=NUM[TOP1];top1--;B=NUM[TOP1];Num[top1]=fun (A,b,ch[top2]);top2--;}Ch[++top2]=str[i];}Else{while (top2>=0&&ch[top2]!= ' ('){A=NUM[TOP1];top1--;B=NUM[TOP1];Num[top1]=fun (A,b,ch[top2]);top2--;}Ch[++top2]=str[i];}}while (top2>=0){A=NUM[TOP1];top1--;B=NUM[TOP1];Num[top1]=fun (A,b,ch[top2]);top2--;}printf ("%.2f\n", num[0]);}return 0;}
Evaluation of an expression