c++利用栈来实现含有加,减,乘,除等基本运算,输出表达式的值
时间: 2024-06-16 16:07:36 浏览: 17
在C++中,可以使用栈来实现含有加、减、乘、除等基本运算并输出表达式的值。具体步骤如下:
1. 创建两个栈,一个用于存储操作数(operand stack),一个用于存储运算符(operator stack)。
2. 遍历表达式的每个字符:
- 如果是数字,则将其转换为操作数,并将操作数压入操作数栈。
- 如果是运算符,则进行以下操作:
- 如果运算符栈为空,或者栈顶运算符为左括号"(",则将当前运算符压入运算符栈。
- 否则,比较当前运算符与栈顶运算符的优先级:
- 如果当前运算符优先级较高,则将当前运算符压入运算符栈。
- 否则,从运算符栈中弹出栈顶运算符,并从操作数栈中弹出两个操作数进行计算,将计算结果压入操作数栈,直到当前运算符的优先级较高或者栈为空。
- 如果是左括号"(",则将其压入运算符栈。
- 如果是右括号")",则进行以下操作:
- 从运算符栈中弹出栈顶运算符,直到遇到左括号"("。
- 弹出左括号"(",丢弃。
3. 遍历完表达式后,如果运算符栈不为空,则从运算符栈中弹出栈顶运算符,并从操作数栈中弹出两个操作数进行计算,将计算结果压入操作数栈,直到运算符栈为空。
4. 最终,操作数栈中的唯一元素即为表达式的值。
下面是一个示例代码:
```cpp
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int calculate(int operand1, int operand2, char op) {
switch (op) {
case '+':
return operand1 + operand2;
case '- operand2;
case '*':
return operand1 * operand2;
case '/':
return operand1 / operand2;
default:
return 0;
}
}
int evaluateExpression(string expression) {
stack<int> operandStack;
stack<char> operatorStack;
for (char c : expression) {
if (isdigit(c)) {
operandStack.push(c - '0');
} else if (c == '(') {
operatorStack.push(c);
} else if (c == ')') {
while (!operatorStack.empty() && operatorStack.top() != '(') {
char op = operatorStack.top();
operatorStack.pop();
int operand2 = operandStack.top();
operandStack.pop();
int operand1 = operandStack.top();
operandStack.pop();
int result = calculate(operand1, operand2, op);
operandStack.push(result);
}
if (!operatorStack.empty() && operatorStack.top() == '(') {
operatorStack.pop();
}
} else {
while (!operatorStack.empty() && operatorStack.top() != '(' &&
((c == '*' || c == '/') || (operatorStack.top() == '+' || operatorStack.top() == '-'))) {
char op = operatorStack.top();
operatorStack.pop();
int operand2 = operandStack.top();
operandStack.pop();
int operand1 = operandStack.top();
operandStack.pop();
int result = calculate(operand1, operand2, op);
operandStack.push(result);
}
operatorStack.push(c);
}
}
while (!operatorStack.empty()) {
char op = operatorStack.top();
operatorStack.pop();
int operand2 = operandStack.top();
operandStack.pop();
int operand1 = operandStack.top();
operandStack.pop();
int result = calculate(operand1, operand2, op);
operandStack.push(result);
}
return operandStack.top();
}
int main() {
string expression;
cout << "请输入表达式:";
cin >> expression;
int result = evaluateExpression(expression);
cout << "表达式的值为:" << result << endl;
return 0;
}
```