- 计算多项式(以下为学长代码,后会更改)
- 思路
- 代码实现
建立操作数栈和运算符栈。运算符有优先级。规则: 自左至右扫描表达式,凡是遇到操作数一律进操作数栈。 当遇到运算符时,如果它的优先级比运算符栈栈顶元素的优先级高就进栈。 反之,取出栈顶运算符和操作数栈栈顶的连续两个操作数进行运算,并将结果存入操作数栈, 然后继续比较该运算符与栈顶运算符的优先级。 左括号一律进运算符栈,右括号一律不进运算符栈, 取出运算符栈顶运算符和操作数栈顶的两个操作数进行运算, 并将结果压入操作数栈,直到取出左括号为止。代码实现
//202031061018 刘知鑫 #include#include #include #include #include using namespace std; stack num; stack op; void eval() { auto b = num.top(); num.pop(); auto a = num.top(); num.pop(); auto c = op.top(); op.pop(); int x; if (c == '+') x = a + b; else if (c == '-') x = a - b; else if (c == '*') x = a * b; else x = a / b; num.push(x); } int main() { unordered_map pr{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}}; string str; cin >> str; for (int i = 0; i < str.size(); i ++ ) { auto c = str[i]; if (isdigit(c)) { int x = 0, j = i; while (j < str.size() && isdigit(str[j])) x = x * 10 + str[j ++ ] - '0'; i = j - 1; num.push(x); } else if (c == '(') op.push(c); else if (c == ')') { while (op.top() != '(') eval(); op.pop(); } else { while (op.size() && op.top() != '(' && pr[op.top()] >= pr[c]) eval(); op.push(c); } } while (op.size()) eval(); cout << num.top() << endl; return 0; }
注:该代码需在较高版本环境下才能运行



