编写一个四则运算的程序,要求加减乘除各定义为一个函数来实现
时间: 2024-05-02 21:18:44 浏览: 97
加减乘除四则运算汇编程序及源代码
5星 · 资源好评率100%
以下是Python语言的实现:
```python
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
if num2 == 0:
print("Error: division by zero")
return None
else:
return num1 / num2
print("Welcome to the calculator program!")
while True:
operation = input("Please enter an operation (+, -, *, /) or 'quit' to exit: ")
if operation == "quit":
break
elif operation not in ["+", "-", "*", "/"]:
print("Invalid operation")
continue
else:
num1 = float(input("Please enter the first number: "))
num2 = float(input("Please enter the second number: "))
if operation == "+":
print(add(num1, num2))
elif operation == "-":
print(subtract(num1, num2))
elif operation == "*":
print(multiply(num1, num2))
elif operation == "/":
print(divide(num1, num2))
```
运行程序后,会提示用户输入一个加减乘除的操作符,然后再输入两个数字。程序根据用户输入的操作符调用相应的函数进行计算,然后输出结果。如果用户输入了无效的操作符,程序会提示用户重新输入。如果用户输入了除数为0的除法操作,程序会输出错误信息。用户输入"quit"可以退出程序。
阅读全文