voideval(){ int b = nums.top(); nums.pop(); int a = nums.top(); nums.pop(); char op = ops.top(); ops.pop(); int x; if (op == '+') x = a+b; elseif (op == '-') x = a-b; elseif (op == '*') x = a*b; else x = a/b; nums.push(x); }
intmain(){ pr['+'] = pr['-'] = 1; pr['*'] = pr['/'] = 2; cin >> s; for (int i = 0; s[i]; i++) { char ch = s[i]; if (isdigit(ch)) { int j = i, x = 0; while (s[j] && isdigit(s[j])) x = x * 10 + s[j++] - '0'; nums.push(x); // 别忘了更新 i 到这个数字的末尾 i = j-1; } elseif (ch == '(') { ops.push(ch); } elseif (ch == ')') { while (ops.top() != '(') eval(); // 把左括号扔掉 ops.pop(); } else { while (ops.size() && pr[ops.top()] >= pr[ch]) eval(); ops.push(ch); } } while (ops.size()) eval(); cout << nums.top() << endl;