用从语言写出算数表达式求值
时间: 2023-10-16 21:07:36 浏览: 32
下面是一个简单的例子,用 Python 语言实现:
```python
expression = "2 + 3 * 4 - 6 / 2" # 待求值的表达式
# 将表达式字符串转换为列表,方便后续处理
tokens = expression.split()
# 定义操作符的优先级和操作数栈
precedence = {'+': 1, '-': 1, '*': 2, '/': 2}
stack = []
# 遍历表达式的每个符号
for token in tokens:
if token.isdigit():
# 如果是数字,则直接压入栈中
stack.append(int(token))
else:
# 如果是操作符,则根据优先级进行处理
while stack and stack[-1] != '(' and precedence[token] <= precedence.get(stack[-1], 0):
operand2 = stack.pop()
operand1 = stack.pop()
if token == '+':
result = operand1 + operand2
elif token == '-':
result = operand1 - operand2
elif token == '*':
result = operand1 * operand2
elif token == '/':
result = operand1 / operand2
stack.append(result)
stack.append(token)
# 处理完所有符号后,栈中剩余的就是表达式的值
while len(stack) > 1:
operand2 = stack.pop()
operand1 = stack.pop()
token = stack.pop()
if token == '+':
result = operand1 + operand2
elif token == '-':
result = operand1 - operand2
elif token == '*':
result = operand1 * operand2
elif token == '/':
result = operand1 / operand2
stack.append(result)
print(stack[0]) # 输出表达式的值
```
以上代码将表达式字符串转换为列表,遍历每个符号,并根据优先级进行处理。具体来说,如果遇到数字,则直接压入栈中;如果遇到操作符,则弹出栈顶的两个数字,并根据操作符计算它们的值,再将结果压入栈中。最终,栈中剩余的就是表达式的值。