编程实现一个简单的计算器,具备加法,减法,乘法,除法,阶乘等运算
时间: 2023-10-08 18:08:38 浏览: 112
好的,以下是 Python 语言的实现示例:
```python
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return "Error: Division by zero is not allowed"
else:
return x / y
def factorial(x):
if x < 0:
return "Error: Factorial of a negative number is not defined"
elif x == 0:
return 1
else:
return x * factorial(x-1)
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
print("5.Factorial")
while True:
choice = input("Enter choice (1/2/3/4/5): ")
if choice in ('1', '2', '3', '4', '5'):
if choice == '5':
num = int(input("Enter a non-negative integer: "))
print(factorial(num))
else:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
break
else:
print("Invalid Input")
```
这个程序会根据用户的选择进行不同的计算操作,使用了函数来实现每种运算,同时还有对除零和负数阶乘的错误处理。
阅读全文