题解 | #简单计算器#
简单计算器
https://www.nowcoder.com/practice/5759c29a28cb4361bc3605979d5a6130
#include <iostream> #include <stack> using namespace std; /* 表示一个运算符的类型以及优先级 栈内:+,- (优先级:3) *,/(优先级:5) 栈外:+,- (优先级:2) *,/(优先级:4) */ struct Node{ char symbol; int order; }; //用于计算 double Calculate(double a,double b,char chr){ double c; if(chr=='+') c=a+b; else if(chr=='-') c=a-b; else if(chr=='*') c=a*b; else if(chr=='/') c=a/b; return c; } //用于从数据栈中取两个数,从符号栈中取一个数,进行运算并压入数据栈中 void Operator(stack<Node> &tag,stack<double> &number){ double a,b,c; char chr; if(!number.empty()) {b=number.top(); number.pop();} if(!number.empty()) {a=number.top(); number.pop();} if(!tag.empty()) {chr=tag.top().symbol; tag.pop();} c=Calculate(a,b,chr); number.push(c); } int main() { string str; while(getline(cin,str)){ if(str.size()==1 && str[0]=='0') break; int num=0; stack<Node> tag; stack<double> number; Node tmp; tmp.symbol='#'; tmp.order=1; tag.push(tmp); for(int i=0;i<str.size();i++){ if(str[i]=='+' || str[i]=='-' || str[i]=='*' || str[i]=='/'){ Node tmp; tmp.symbol=str[i]; if(str[i]=='+' || str[i]=='-') tmp.order=2; else tmp.order=4; //如果当前符号优先级小于栈中符号的,则先把栈中的计算完,这里要写while而不是if while(tmp.order<tag.top().order){ Operator(tag,number); } //若当前符号优先级大于栈中符号的,则压栈 if(tmp.order>tag.top().order){ tmp.order++; tag.push(tmp); } } //字符转数字,以空格为停止 else if(str[i]>='0' && str[i]<='9'){ num=num*10+(str[i]-'0'); if(i==str.size()-1) {number.push(num); num=0;} } else if(str[i]==' ' && (str[i-1]>='0' && str[i-1]<='9')){ //调试才发现符号后也会出现空格,之前被我忽略掉了 number.push(num); num=0; } } while(tag.size()>1){ Operator(tag,number); } printf("%.2f\n",number.top()); number.pop(); } return 0; }