标签:
1 + 2 4 + 2 * 5 - 7 / 11 0
3.00 13.36
#include <cstdio> #include <cstring> #include <algorithm> #include <stack> using namespace std; const int MAXN=1005; char s[MAXN]; bool isOp(char op) { if(op==‘+‘||op==‘-‘||op==‘*‘||op==‘/‘) return true; else return false; } int Priority(char op) { switch(op) { case ‘+‘:return 1; case ‘-‘:return 1; case ‘*‘:return 2; case ‘/‘:return 2; } } double cal(double x,double y,char op) { switch(op) { case ‘+‘:return x+y; case ‘-‘:return x-y; case ‘*‘:return x*y; case ‘/‘:return x/y; } } char ss[MAXN]; int top; int main() { while(gets(s)&&strcmp(s,"0")!=0) { top=0; stack<char> op; stack<double> it; int len=strlen(s); for(int i=0;i<len;i++) { if(s[i]==‘ ‘) continue; ss[top++]=s[i]; } int e=0; for(int i=0;i<top;i++) { if(isOp(ss[i])) { it.push(double(e)); e=0; if(op.empty()) { op.push(ss[i]); } else { int pri1=Priority(ss[i]); int pri2=Priority(op.top()); if(pri1>pri2) { op.push(ss[i]); } else { do{ double x=it.top();it.pop(); double y=it.top();it.pop(); double res=cal(y,x,op.top()); op.pop(); it.push(res); }while(!op.empty()&&pri1<=Priority(op.top())); op.push(ss[i]); } } } else { e*=10; e=e+ss[i]-‘0‘; } } it.push(double(e)); while(it.size()>1) { double x=it.top();it.pop(); double y=it.top();it.pop(); double res=cal(y,x,op.top());op.pop(); it.push(res); } double res=it.top(); printf("%.2lf\n",res); } return 0; }
标签:
原文地址:http://www.cnblogs.com/program-ccc/p/5500062.html