只利用中缀形式编写代码实现简易计算器
时间: 2024-02-13 11:06:01 浏览: 24
好的,我来给你提供一个仅使用中缀表达式实现的简易计算器的Python代码:
```python
import math
# 定义操作符的优先级
priority = {'+': 1, '-': 1, '*': 2, '/': 2, '%': 2, '√': 3, '^': 4}
# 判断是否为数字
def is_number(token):
try:
float(token)
return True
except ValueError:
return False
# 计算表达式的值
def calculate(expr):
num_stack = []
op_stack = []
tokens = expr.split()
for token in tokens:
if is_number(token):
num_stack.append(float(token))
elif token == '(':
op_stack.append(token)
elif token == ')':
top_token = op_stack.pop()
while top_token != '(':
num2 = num_stack.pop()
num1 = num_stack.pop()
if top_token == '+':
num_stack.append(num1 + num2)
elif top_token == '-':
num_stack.append(num1 - num2)
elif top_token == '*':
num_stack.append(num1 * num2)
elif top_token == '/':
num_stack.append(num1 / num2)
elif top_token == '%':
num_stack.append(num1 % num2)
elif top_token == '√':
num_stack.append(math.sqrt(num2))
elif top_token == '^':
num_stack.append(num1 ** num2)
top_token = op_stack.pop()
else:
while op_stack and priority[op_stack[-1]] >= priority[token]:
top_token = op_stack.pop()
num2 = num_stack.pop()
num1 = num_stack.pop()
if top_token == '+':
num_stack.append(num1 + num2)
elif top_token == '-':
num_stack.append(num1 - num2)
elif top_token == '*':
num_stack.append(num1 * num2)
elif top_token == '/':
num_stack.append(num1 / num2)
elif top_token == '%':
num_stack.append(num1 % num2)
elif top_token == '√':
num_stack.append(math.sqrt(num2))
elif top_token == '^':
num_stack.append(num1 ** num2)
op_stack.append(token)
while op_stack:
top_token = op_stack.pop()
num2 = num_stack.pop()
num1 = num_stack.pop()
if top_token == '+':
num_stack.append(num1 + num2)
elif top_token == '-':
num_stack.append(num1 - num2)
elif top_token == '*':
num_stack.append(num1 * num2)
elif top_token == '/':
num_stack.append(num1 / num2)
elif top_token == '%':
num_stack.append(num1 % num2)
elif top_token == '√':
num_stack.append(math.sqrt(num2))
elif top_token == '^':
num_stack.append(num1 ** num2)
return num_stack.pop()
# 主程序
while True:
expr = input('请输入表达式(支持的操作符包括+、-、*、/、%、(、)、√和^):')
try:
result = calculate(expr)
print('计算结果为:', result)
except:
print('表达式非法,请重新输入!')
```
这个代码实现了一个简易计算器,它可以接受用户输入的中缀表达式,并计算出表达式的结果。如果表达式非法,则会输出错误信息。你可以在此基础上进行修改和扩展,实现更复杂的功能,比如添加界面等。