编程模拟一个简单的计算器,从键盘按照a+或减乘除b的格式输入一个表达式,其中a和b是实数。
时间: 2024-10-23 10:05:18 浏览: 9
你可以通过编写一个简单的命令行程序来模拟一个基本的计算器。下面是一个使用Python编写的示例:
```python
def addsubtract(num1, operator, num2):
if operator == '+':
return num1 + num2
elif operator == '-':
return num1 - num2
else:
raise ValueError("Invalid operator. Only '+' and '-' are supported.")
def multiplydivide(num1, operator, num2):
if operator == '*':
return num1 * num2
elif operator == '/':
if num2 != 0:
return num1 / num2
else:
raise ZeroDivisionError("Cannot divide by zero.")
else:
raise ValueError("Invalid operator. Only '*' and '/' are supported.")
try:
expression = input("请输入表达式 (格式: a+/-*/*b): ")
parts = expression.split()
a = float(parts[0])
operator = parts[1]
b = float(parts[2])
result = None
if len(parts) == 3:
result = addsubtract(a, operator, b)
elif len(parts) == 4:
result = multiplydivide(a, operator, b)
print(f"计算结果: {result}")
except ValueError as ve:
print("错误:", str(ve))
except ZeroDivisionError as zde:
print("错误:", str(zde))
阅读全文