用他一生写一个简易的四则运算器 要求传入的是字符串 输出为保留两位小数
时间: 2024-12-15 14:23:47 浏览: 14
为了编写一个简单的四则运算器,我们可以使用Python语言。下面是一个简易版本,它会接受输入的字符串形式的数学表达式,并返回计算结果,保留两位小数:
```python
def calculate_expression(expression):
def apply_operator(operators, values):
operator = operators.pop()
right = values.pop()
left = values.pop()
if operator == '+':
return left + right
elif operator == '-':
return left - right
elif operator == '*':
return left * right
elif operator == '/':
try:
return round(left / right, 2)
except ZeroDivisionError:
print("错误:除数不能为零")
return None
def greater_precedence(op1, op2):
precedence = {'+': 1, '-': 1, '*': 2, '/': 2}
return precedence[op1] > precedence[op2]
operators = []
values = []
i = 0
while i < len(expression):
if expression[i].isdigit():
j = i
while j < len(expression) and expression[j].isdigit():
j += 1
values.append(int(expression[i:j]))
i = j
elif expression[i] in ['+', '-', '*', '/']:
while (operators and greater_precedence(operators[-1], expression[i])):
result = apply_operator(operators, values)
if result is not None:
values.append(result)
operators.append(expression[i])
else:
i += 1
# Apply remaining operators
while operators:
result = apply_operator(operators, values)
if result is not None:
values.append(result)
# Return the final value
if len(values) == 1:
return values[0]
else:
raise ValueError("无法解析表达式")
# 测试示例
expression_str = "2 + 3 * 4.567"
try:
result = calculate_expression(expression_str)
print(f"结果:{result:.2f}")
except ValueError as e:
print(e)
```
这个计算器只处理了基本的算术操作和小数点,对于复杂的表达式或者括号,需要进一步完善。如果你想要输入包含括号的表达式,可能需要使用递归逆波兰表示法(RPN)或其他算法来处理。
阅读全文