表达式求值
时间限制:
3000 ms | 内存限制:
65535 KB
难度:
4
-
描述
-
ACM队的mdd想做一个计算器,但是,他要做的不仅仅是一计算一个A+B的计算器,他想实现随便输入一个表达式都能求出它的值的计算器,现在请你帮助他来实现这个计算器吧。
比如输入:“1+2/4=”,程序就输出1.50(结果保留两位小数)-
输入
-
第一行输入一个整数n,共有n组测试数据(n<10)。
每组测试数据只有一行,是一个长度不超过1000的字符串,表示这个运算式,每个运算式都是以“=”结束。这个表达式里只包含+-*/与小括号这几种符号。其中小括号可以嵌套使用。数据保证输入的操作数中不会出现负数。
数据保证除数不会为0
输出
- 每组都输出该组运算式的运算结果,输出结果保留两位小数。 样例输入
-
2 1.000+2/4= ((1+2)*5+1)/4=
样例输出
-
1.50 4.00
来源
- 数据结构课本例题改进 上传者
【分析】先把中缀表达式转换为逆波兰表达式,然后求值。
#include <cstdio> #include <cmath> #include <stack> #include <cstring> #include <string> using namespace std; const int maxn = 1005; char s1[maxn]; string s2; stack<char>ch; stack<double>num; int judge(char x){ switch (x){ case '+': case '-':return 1; case '*': case '/':return 2; default:return 0; } } void init(){ int len = strlen(s1); while (!ch.empty()) ch.pop(); while (!num.empty()) num.pop(); ch.push('#'); s2 = ""; int i=0; while (i<len-1){ if (s1[i]=='(') ch.push(s1[i++]); else if (s1[i]==')') { while (ch.top()!='(') { s2+=ch.top(); s2+=' '; ch.pop(); } ch.pop(); i++; } else if (s1[i]=='+' || s1[i]=='-' || s1[i]=='*' || s1[i]=='/') { while (judge(ch.top())>=judge(s1[i])){ s2+=ch.top(); s2+=' '; ch.pop(); } ch.push(s1[i++]); } else { while (s1[i]>='0' && s1[i]<='9' || s1[i]=='.') s2+=s1[i++]; s2+=' '; } } while (ch.top()!='#'){ s2+=ch.top(); s2+=' '; ch.pop(); } } double cnt(){ int len = s2.length(); double x,y,tmp; int i = 0; while (i<len){ if (s2[i]==' ') i++; else { switch (s2[i]){ case '+':x=num.top(); num.pop(); x+=num.top(); num.pop();i++; break; case '-':x=num.top(); num.pop(); x=num.top()-x; num.pop(); i++; break; case '*':x=num.top(); num.pop(); x*=num.top(); num.pop(); i++; break; case '/':x=num.top(); num.pop(); x=num.top()/x; num.pop(); i++; break; default:{ x = 0.0; while (s2[i]>='0' && s2[i]<='9') x=x*10+s2[i++]-'0'; if (s2[i]=='.'){ i++; tmp = 10.0; y = 0.0; while (s2[i]>='0' && s2[i]<='9') { y+=(s2[i++]-'0')/tmp; tmp*=10; } x+=y; } } } num.push(x); } } return num.top(); } int main(){ int T; scanf("%d",&T); while(T--){ scanf("%s",s1); init(); printf("%.2lf\n",cnt()); } return 0; }
-
第一行输入一个整数n,共有n组测试数据(n<10)。