接受用户输入的四则运算表达式,使用栈进行表达式求值。不考虑括号。
时间: 2024-02-16 10:59:39 浏览: 29
好的,我可以帮你解答这个问题。
首先,我们需要定义一个操作符栈和一个操作数栈,用于存储操作符和操作数。然后,我们遍历表达式中的每个字符,如果是数字,就将其转化为数字类型,并压入操作数栈中;如果是操作符,就将其压入操作符栈中。
当遇到下一个操作符时,如果该操作符的优先级比操作符栈顶的操作符优先级低,就将操作数栈中的两个操作数弹出,并将操作符栈顶的操作符弹出,进行运算,并将结果压入操作数栈中。重复这个过程,直到遇到的操作符优先级比操作符栈顶的操作符优先级高为止,然后将该操作符压入操作符栈中。
最后,当表达式遍历完成后,操作符栈中可能还存在操作符,需要继续进行运算,直到操作符栈为空为止。最终的结果即为操作数栈中的唯一元素。
下面是一个使用栈求解表达式的示例代码(仅支持四则运算):
```python
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def is_empty(self):
return len(self.items) == 0
def evaluate(expression):
operator_stack = Stack()
operand_stack = Stack()
operators = set(['+', '-', '*', '/'])
for char in expression:
if char.isdigit():
operand_stack.push(int(char))
elif char in operators:
while not operator_stack.is_empty() and operator_stack.items[-1] in operators and precedence(char) <= precedence(operator_stack.items[-1]):
op = operator_stack.pop()
right_operand = operand_stack.pop()
left_operand = operand_stack.pop()
result = evaluate_expression(left_operand, right_operand, op)
operand_stack.push(result)
operator_stack.push(char)
while not operator_stack.is_empty():
op = operator_stack.pop()
right_operand = operand_stack.pop()
left_operand = operand_stack.pop()
result = evaluate_expression(left_operand, right_operand, op)
operand_stack.push(result)
return operand_stack.pop()
def precedence(operator):
if operator == '+' or operator == '-':
return 1
elif operator == '*' or operator == '/':
return 2
else:
return 0
def evaluate_expression(left_operand, right_operand, operator):
if operator == '+':
return left_operand + right_operand
elif operator == '-':
return left_operand - right_operand
elif operator == '*':
return left_operand * right_operand
elif operator == '/':
return left_operand / right_operand
expression = input('请输入四则运算表达式:')
result = evaluate(expression)
print('结果为:', result)
```
希望这个例子能够对你有所帮助!