题解 | 计算表达式
计算表达式
https://www.nowcoder.com/practice/7b18aa6b7cc14f8eaae6b8acdebf890b
#include<stdio.h>
#include<stack>
#include<string>
#include<map>
#include <iostream>
using namespace std;
//计算:弹出一个运算符和两个左右操作数计算
void fun(stack<char>& opStr, stack<double>& numStr) {
double numR = numStr.top();
numStr.pop();
double numL = numStr.top();
numStr.pop();
char topOp = opStr.top();
opStr.pop();
double res = 0;
if (topOp == '+') res = numL + numR;
if (topOp == '-') res = numL - numR;
if (topOp == '*') res = numL * numR;
if (topOp == '/') res = numL / numR;
numStr.push(res);
}
int main() {
stack<char> opStr;
stack<double> numStr;
map<char, int> priOP = { {'+', 1}, {'-', 1}, {'*', 2}, {'/', 2} };
string str;
getline(cin, str);
// 1. 遍历字符串
for (int i = 0; i < str.size(); ) {
// 注意:这里去掉了 for 的第三个参数,手动控制 i
if (str[i] >= '0' && str[i] <= '9') {
// 1.1 处理数字:拼接连续数字
string num = "";
while (i < str.size() && str[i] >= '0' && str[i] <= '9') {
num += str[i];
i++; //自增 i
}
numStr.push(stod(num));
} else {
// 1.2 处理运算符 (+, -, *, /)
// 注意:这里 i 不需要自增,因为 for 循环末尾会处理
char op = str[i];
// 如果栈顶运算符优先级 >= 当前运算符,就先算栈顶的
// 注意:必须先判断 !opStr.empty(),利用短路避免崩溃
while (!opStr.empty() && priOP[opStr.top()] >= priOP[op]) {
fun(opStr,numStr);
}
// 当前运算符压栈
opStr.push(op);
i++; // 处理完运算符,i 自增
}
}
// 2. 处理栈里剩下的运算符
while (!opStr.empty()) {
fun(opStr,numStr);
}
// 3. 输出结果
printf("%d\n", (int) numStr.top()); // 输出整数形式
return 0;
}
计算机复试机试(王道版) 文章被收录于专栏
收录王道2026年计算机复试机试的(课程)代码题解,仅供个人学习参考
