题解 | #简单计算器#
简单计算器
http://www.nowcoder.com/practice/5759c29a28cb4361bc3605979d5a6130
#include<iostream> #include<string> #include<stack> #include<cctype> using namespace std; //优先级顺序#,$,+-,*/ int priority(char c) { if(c=='#') { return 0; } else if(c=='$') { return 1; } else if(c=='+'||c=='-') { return 2; } else { return 3; } } //获得数字 double getNumber(string str,int& index) { double number=0; while(isdigit(str[index])) { number=number*10+str[index]-'0'; index++; } return number; } double Calculate(double x,double y,char op) { double ans=0; if(op=='+') { ans=x+y; } else if(op=='-') { ans=x-y; } else if(op=='*') { ans=x*y; } else if(op=='/') { ans=x/y; } return ans; } int main() { string str; while(getline(cin,str)) { if(str=="0") { break; } int index=0; stack<char> operation; stack<double> number; str+='$'; operation.push('#'); while(index<str.size()) { if(str[index]==' ') { index++; //向后继续扫描 } else if(isdigit(str[index])) { double tt=getNumber(str,index); //将运算数压入栈中 number.push(tt); } else { if(priority(operation.top())<priority(str[index])) //比较栈顶运算符与当前运算符 { operation.push(str[index]); //将当前运算符压入栈中 index++; } else { double y=number.top(); //可运算的局部区域,依次弹出数字栈顶与次栈顶进行运算 number.pop(); double x=number.top(); number.pop(); number.push(Calculate(x,y,operation.top())); //将计算结果放入数字栈中 operation.pop(); } } } printf("%0.2f\n",number.top()); //输出数字栈栈顶 } return 0; }