题解 | #计算表达式#
计算表达式
https://www.nowcoder.com/practice/7b18aa6b7cc14f8eaae6b8acdebf890b
#include <iostream> #include <stack> using namespace std; bool isOp(char op){ if (op=='+' || op=='-' || op=='*' || op=='/' || op=='#'){ return true; } return false; } double yunsuan(double x, double y, char op){ switch (op) { case '+': return x+y; case '-': return x-y; case '*': return x*y; case '/': return x/y; default: return 0; } } int priority(char op){ if (op=='*' || op=='/'){ return 2; } else if (op=='+' || op=='-'){ return 1; } else{ return 0; } } int main() { string str; while (getline(cin,str)){ if (str=="0") break; str.push_back('#'); stack<double> numStack; stack<char> opStack; string num; for (int i = 0; i < str.size(); ++i) { if (str[i]>='0' && str[i]<='9'){ num.push_back(str[i]); } else{ numStack.push(stod(num)); num = ""; while (!opStack.empty() && priority(opStack.top())>= priority(str[i])){ char oper = opStack.top(); opStack.pop(); double y = numStack.top(); numStack.pop(); double x = numStack.top(); numStack.pop(); double result = yunsuan(x,y,oper); numStack.push(result); } opStack.push(str[i]); } } // printf("%.2lf\n",numStack.top()); printf("%.0lf\n",numStack.top()); } return 0; }