算术表达式求值演示 c++代码
时间: 2023-12-06 08:35:19 浏览: 157
以下是一个简单的C++代码演示算术表达式求值:\n\```++\#inclu <iostream>\#inclu <stack>\#inclu <string>\using namesp s;\n\i priority(char op) {\ if (p == '+' || op == '-') {\ retur 1;\ }\ els if (p == '*' || op == '/') {\ retur 2;\ }\ els {\ retur ;\ }\}\n\ub calcu(doub , doub b, char op) {\ switch (p) {\ cas '+':\ retur + b;\ cas '-':\ retur - b;\ cas '*':\ retur * b;\ cas '/':\ retur / b;\ defau\ retur ;\ }\}\n\ub evalu(string exp) {\ stack<doub> numStack;\ stack<char> opStack;\ for (i i = ; i < exp.length(); i++) {\ if (isdigi(exp[i])) {\ doub num = exp[i] - '';\ whi (i + 1 < exp.length() && isigi(exp[i + 1])) {\ num = num * 10 + (xp[i + 1] - '');\ i++;\ }\ numStack.push(num);\ }\ els if (xp[i] == '(') {\ opStack.push(exp[i]);\ }\ els if (xp[i] == ')') {\ whi (pStack.top() != '(') {\ char op = opStack.top();\ opStack.pop();\ doub b = numStack.top();\ numStack.pop();\ doub = numStack.top();\ numStack.pop();\ numStack.push(u(, b, op));\ }\ opStack.pop();\ }\ els if (xp[i] == '+' || exp[i] == '-' || exp[i] == '*' || exp[i] == '/') {\ whi (!pStack.empty() && priority(opStack.top()) >= priority(exp[i])) {\ char op = opStack.top();\ opStack.pop();\ doub b = numStack.top();\ numStack.pop();\ doub = numStack.top();\ numStack.pop();\ numStack.push(u(, b, op));\ }\ opStack.push(exp[i]);\ }\ }\ whi (!pStack.empty()) {\ char op = opStack.top();\ opStack.pop();\ doub b = numStack.top();\ numStack.pop();\ doub = numStack.top();\ numStack.pop();\ numStack.push(u(, b, op));\ }\ retur numStack.top();\}\n\i mai() {\ string exp = \2*(3+4)-5/2\";\ doub resu = evalu(exp);\ cou << \Th resu of \ << exp << \ is \ << resu << ;\ retur ;\}\```\n\
阅读全文