C++ 中缀表达式计算器:带中文注释的代码实现
#include
// 定义优先级函数,返回运算符的优先级 int priority(char op) { if (op == '+' || op == '-') { return 1; } if (op == '*' || op == '/') { return 2; } return 0; }
// 定义计算函数,返回计算结果 int calculate(int num1, int num2, char op) { if (op == '+') { return num1 + num2; } if (op == '-') { return num1 - num2; } if (op == '*') { return num1 * num2; } if (op == '/') { return num1 / num2; } return 0; }
int main() {
string expression; // 存放中缀表达式的字符串
stack
// 输入中缀表达式
cout << '请输入中缀表达式:' << endl;
getline(cin, expression);
// 遍历中缀表达式
for (int i = 0; i < expression.length(); i++) {
char c = expression[i];
// 如果是数字,入栈
if (isdigit(c)) {
int num = 0;
while (isdigit(c)) {
num = num * 10 + (c - '0');
i++;
c = expression[i];
}
numStack.push(num);
i--; // 退回到数字的最后一位
}
// 如果是左括号,入栈
else if (c == '(') {
opStack.push(c);
}
// 如果是右括号,弹出栈中运算符,并计算结果,直到遇到左括号
else if (c == ')') {
while (!opStack.empty() && opStack.top() != '(') {
int num2 = numStack.top();
numStack.pop();
int num1 = numStack.top();
numStack.pop();
char op = opStack.top();
opStack.pop();
int result = calculate(num1, num2, op);
numStack.push(result);
}
opStack.pop(); // 弹出左括号
}
// 如果是运算符,判断其优先级,若比栈顶运算符优先级高或相等,则入栈,否则弹出栈中运算符并计算结果,直到优先级高或相等
else if (c == '+' || c == '-' || c == '*' || c == '/') {
while (!opStack.empty() && priority(opStack.top()) >= priority(c)) {
int num2 = numStack.top();
numStack.pop();
int num1 = numStack.top();
numStack.pop();
char op = opStack.top();
opStack.pop();
int result = calculate(num1, num2, op);
numStack.push(result);
}
opStack.push(c);
}
}
// 遍历完中缀表达式后,如果栈中还有运算符,则弹出并计算结果
while (!opStack.empty()) {
int num2 = numStack.top();
numStack.pop();
int num1 = numStack.top();
numStack.pop();
char op = opStack.top();
opStack.pop();
int result = calculate(num1, num2, op);
numStack.push(result);
}
// 输出计算结果
cout << '计算结果为:' << numStack.top() << endl;
return 0;
}
原文地址: https://www.cveoy.top/t/topic/npr7 著作权归作者所有。请勿转载和采集!