标签:
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; }
标签:
原文地址:http://www.cnblogs.com/program-ccc/p/5651070.html