用python写一个计算器程序支持,加,减,乘,除,幂运算,取整,求余
时间: 2024-12-08 08:18:49 浏览: 3
基于Python编写一个计算器程序,实现简单的加减乘除和取余二元运算
5星 · 资源好评率100%
你可以使用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 x / y
else:
print("Error! Division by zero is not allowed.")
return None
def power(x, y):
return x ** y
def floor_division(x, y):
return x // y
def modulus(x, y):
return x % y
print("Welcome to Simple Calculator!")
while True:
print("\nOptions:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Power (Exponentiation)")
print("6. Floor Division")
print("7. Modulus (Remainder)")
print("8. Exit")
choice = input("Enter your choice (1-8): ")
if choice == '8':
break
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if choice in ['1', '2', '3', '4']:
result = locals()[f"{choice.lower()}"](num1, num2)
print(f"Result: {result}")
elif choice == '5':
result = power(num1, num2)
print(f"Result: {result}")
elif choice == '6':
result = floor_division(num1, num2)
print(f"Result: {result}")
elif choice == '7':
result = modulus(num1, num2)
print(f"Result: {result}")
else:
print("Invalid choice. Please try again.")
阅读全文