- 题目描述:
-
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
- 输入:
-
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
- 输出:
-
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
- 样例输入:
-
1 + 2 4 + 2 * 5 - 7 / 11 0
- 样例输出:
-
3.00 13.36
#include <iostream> #include <stack> #include <iomanip> #include <string.h> using namespace std; const int MAXN=205; char buf[MAXN]; bool isNum(char ch) { return '0'<=ch&&ch<='9'; } int priority(char ch) { switch(ch) { case '+':return 1; case '-':return 1; case '*':return 2; case '/':return 2; } } double cal(char ch,double x,double y) { switch(ch) { case '+':return x+y; case '-':return x-y; case '*':return x*y; case '/':return x/y; } } int main() { while(cin.getline(buf,MAXN)) { if(strlen(buf)==1&&buf[0]=='0') break; stack<double> it; stack<char> op; double x=0; for(int i=0;buf[i];i++) { if(buf[i]==' ') continue; if(isNum(buf[i])) { x*=10; x+=(buf[i]-'0'); } else { it.push(x); x=0; if(op.empty()) { op.push(buf[i]); } else { char now=buf[i]; char tp=op.top(); int pn=priority(now); int pt=priority(tp); if(pn>pt) { op.push(now); } else { do { tp=op.top();op.pop(); double y=it.top();it.pop(); double x=it.top();it.pop(); double res=cal(tp,x,y); it.push(res); if(op.empty()) break; pt=priority(op.top()); }while(pn<=pt); op.push(now); } } } } it.push(x); while(!op.empty()) { char now=op.top();op.pop(); double y=it.top();it.pop(); double x=it.top();it.pop(); double res=cal(now,x,y); it.push(res); } double res=it.top(); /*C++输出两位小数*/ cout.setf(ios::showpoint); cout.precision(2); cout.setf(ios::fixed); cout<<res<<endl; } return 0; }
简洁代码:
#include <cstdio> using namespace std; const int MAXN=1005; double e[MAXN]; int main() { double x; char op; while(scanf("%lf%c",&x,&op)!=EOF) { if(x==0&&op==' ') break; int top=0; e[top++]=x; while(scanf("%c",&op)!=EOF) { scanf(" %lf",&x); switch(op) { case '+':e[top++]=x;break; case '-':e[top++]=-x;break; case '*':e[top-1]*=x;break; case '/':e[top-1]/=x;break; } if(getchar()==' ') break; } double res=0; for(int i=0;i<top;i++) { res+=e[i]; } printf("%.2f ",res); } return 0; }