温馨提示:此版本为U.C.1.5.0,不支持小数计算
1.5.0更新内容:
1、括号嵌套数量上线增加到20
2、修改BUG
上代码:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
// 操作符的优先级
int getPriority(char op) {
if (op == '+' || op == '-')
return 1;
if (op == '*' || op == '/')
return 2;
return 0;
}
// 计算两个数的结果
int calculate(int num1, int num2, char op) {
switch (op) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num1 / num2;
default:
return 0;
}
}
// 计算表达式的结果
int evaluate(string expression) {
stack<int> numberStack; // 存放数字
stack<char> operatorStack; // 存放操作符
for (int i = 0; i < expression.length(); i++) {
if (isdigit(expression[i])) {
int num = 0;
// 将连续的数字字符转换为整数
while (i < expression.length() && isdigit(expression[i])) {
num = num * 10 + (expression[i] - '0');
i++;
}
// 将整数压入数字栈
numberStack.push(num);
// 因为for循环中有i++,所以要回退一位
i--;
} else if (expression[i] == '(') {
// 左括号直接入操作符栈
operatorStack.push('(');
} else if (expression[i] == ')') {
// 右括号计算括号内的表达式
while (!operatorStack.empty() && operatorStack.top() != '(') {
char op = operatorStack.top();
operatorStack.pop();
int num2 = numberStack.top();
numberStack.pop();
int num1 = numberStack.top();
numberStack.pop();
int result = calculate(num1, num2, op);
numberStack.push(result);
}
// 弹出左括号
if (!operatorStack.empty() && operatorStack.top() == '(') {
operatorStack.pop();
}
} else if (expression[i] == '+' || expression[i] == '-' || expression[i] == '*' || expression[i] == '/') {
// 当前操作符的优先级小于等于栈顶操作符的优先级时,先计算栈顶的操作符
while (!operatorStack.empty() && operatorStack.top() != '(' && getPriority(expression[i]) <= getPriority(operatorStack.top())) {
char op = operatorStack.top();
operatorStack.pop();
int num2 = numberStack.top();
numberStack.pop();
int num1 = numberStack.top();
numberStack.pop();
int result = calculate(num1, num2, op);
numberStack.push(result);
}
// 将当前操作符入操作符栈
operatorStack.push(expression[i]);
}
}
// 计算剩余的表达式
while (!operatorStack.empty() && operatorStack.top() != '(') {
char op = operatorStack.top();
operatorStack.pop();
int num2 = numberStack.top();
numberStack.pop();
int num1 = numberStack.top();
numberStack.pop();
int result = calculate(num1, num2, op);
numberStack.push(result);
}
// 返回最终结果
return numberStack.top();
}
int main() {
string expression;
cout << "请输入表达式:";
getline(cin, expression);
int result = evaluate(expression);
cout << "结果:" << result << endl;
return 0;
}