编程实现一个简单的计算器。此计算器应具备基本计算功能:加法、减法、乘法、除法、阶乘等运算,请利用模块化程序设计的思想设计实现。提示:可利用有参有返回值函数实现计算器的各项功能。
时间: 2023-12-18 22:03:01 浏览: 42
好的,我可以帮你解决这个问题。下面是一个简单的计算器的实现代码:
```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):
return x / y
# 定义阶乘函数
def factorial(x):
if x == 1:
return 1
else:
return x * factorial(x-1)
# 主函数
def main():
print("请选择要进行的运算:")
print("1.加法")
print("2.减法")
print("3.乘法")
print("4.除法")
print("5.阶乘")
choice = input("请输入您的选择(1/2/3/4/5):")
if choice in ('1', '2', '3', '4'):
num1 = float(input("请输入第一个数字:"))
num2 = float(input("请输入第二个数字:"))
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))
elif choice == '5':
num = int(input("请输入一个正整数:"))
print(num, "的阶乘是:", factorial(num))
else:
print("输入有误,请重新输入。")
if __name__ == "__main__":
main()
```
这个计算器程序中,我们定义了加法、减法、乘法、除法、阶乘等函数。在主函数中,我们输出了菜单,让用户选择要进行哪种运算。根据用户的选择,我们调用相应的函数进行计算,并输出结果。
需要注意的是,我们在除法函数中没有处理除数为0的情况。在实际的程序开发中,应该对这种情况进行处理,以避免程序出错。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)