算数表达式求值 栈c++
时间: 2023-10-30 18:09:12 浏览: 153
算数表达式求值可以使用栈来实现,以下是一个简单的实现示例:
```python
def evaluate_expression(expression):
# 定义操作符优先级
precedence = {'+': 1, '-': 1, '*': 2, '/': 2}
# 定义操作数栈和操作符栈
operand_stack = []
operator_stack = []
# 辅助函数:执行操作符计算
def apply_operator():
operator = operator_stack.pop()
operand2 = operand_stack.pop()
operand1 = operand_stack.pop()
if operator == '+':
result = operand1 + operand2
elif operator == '-':
result = operand1 - operand2
elif operator == '*':
result = operand1 * operand2
elif operator == '/':
result = operand1 / operand2
operand_stack.append(result)
# 遍历表达式计算结果
for char in expression:
if char.isdigit():
operand_stack.append(int(char))
elif char in ['+', '-', '*', '/']:
while (operator_stack and operator_stack[-1] != '(' and
precedence[char] <= precedence[operator_stack[-1]]):
apply_operator()
operator_stack.append(char)
elif char == '(':
operator_stack.append(char)
elif char == ')':
while operator_stack[-1] != '(':
apply_operator()
operator_stack.pop()
while operator_stack:
apply_operator()
return operand_stack[-1]
expression = input("请输入算数表达式: ")
result = evaluate_expression(expression)
print(f"表达式的计算结果为: {result}")
```
这段代码可以读入一个算术表达式,并使用栈来求值。注意,这里只考虑了简单的四则运算,没有处理复杂的情况如函数调用、括号嵌套等。
阅读全文