c++利用栈完成加减乘除及带括号的四则混合整数运算
时间: 2024-02-20 18:57:06 浏览: 23
好的,我可以为您解答这个问题。首先,您需要定义一个栈来存储中间结果和操作符。具体的做法是,读入一个整数或操作符时,如果是整数就直接入栈,如果是操作符就将其与栈顶操作符进行比较,如果优先级高于栈顶操作符,则直接入栈,否则将栈顶操作符弹出并进行相应的计算,然后将计算结果入栈。最终,栈中只剩下一个整数,即为最终的计算结果。
以下是一个示例代码:
```c++
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int priority(char op) {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
return 0;
}
int calculate(stack<int>& nums, stack<char>& ops) {
int num2 = nums.top(); nums.pop();
int num1 = nums.top(); nums.pop();
char op = ops.top(); ops.pop();
switch (op) {
case '+': return num1 + num2;
case '-': return num1 - num2;
case '*': return num1 * num2;
case '/': return num1 / num2;
default: return 0;
}
}
int evaluate(string expr) {
stack<int> nums;
stack<char> ops;
for (int i = 0; i < expr.size(); i++) {
if (isdigit(expr[i])) {
int num = 0, j = i;
while (j < expr.size() && isdigit(expr[j])) {
num = num * 10 + (expr[j] - '0');
j++;
}
nums.push(num);
i = j - 1;
} else if (expr[i] == '(') {
ops.push(expr[i]);
} else if (expr[i] == ')') {
while (ops.top() != '(') {
nums.push(calculate(nums, ops));
}
ops.pop();
} else if (expr[i] == '+' || expr[i] == '-' ||
expr[i] == '*' || expr[i] == '/') {
while (!ops.empty() && priority(ops.top()) >= priority(expr[i])) {
nums.push(calculate(nums, ops));
}
ops.push(expr[i]);
}
}
while (!ops.empty()) {
nums.push(calculate(nums, ops));
}
return nums.top();
}
int main() {
string expr = "((2+3)*5-8)/4";
int result = evaluate(expr);
cout << result << endl;
return 0;
}
```
这段代码实现了带括号的四则混合整数运算,您可以根据自己的需要进行修改。