题解 | 计算表达式
计算表达式
https://www.nowcoder.com/practice/7b18aa6b7cc14f8eaae6b8acdebf890b
#include <iostream> #include<stack> using namespace std; bool opPriority(char op1, char op2) { if ((op1 == '/' || op1 == '*') && (op2 == '-' || op2 == '+'))return true; return false; } double caculate(double a, double b, char op) { switch (op) { case '-': return a - b; case '+': return a + b; case '/': return a / b; case '*': return a * b; } return 0; } int main() { string s; while (cin >> s) { // 注意 while 处理多个 case stack<double>numstack; stack<char>opstack; for (int i = 0; i < s.length();) { double num = 0; int flag=1; if(i==0&&s[i]=='-'){ flag=-1; i++; } if(isdigit(s[i])){ while (isdigit(s[i])) { num = num * 10 + s[i] - '0'; i++; } if(flag==-1)num=-num; numstack.push(num); }else if (opstack.empty() || opPriority(s[i], opstack.top())){ opstack.push(s[i]); i++; }else { while (!opstack.empty() && !opPriority(s[i], opstack.top())) { double a = numstack.top();numstack.pop(); double b = numstack.top();numstack.pop(); numstack.push(caculate(b, a, opstack.top())); opstack.pop(); } opstack.push(s[i]); i++; } } while(!opstack.empty()){ double a=numstack.top();numstack.pop(); double b=numstack.top();numstack.pop(); numstack.push(caculate(b, a, opstack.top()));opstack.pop(); } cout<<numstack.top()<<endl; } } // 64 位输出请用 printf("%lld")