写一个计算器实现加减法
时间: 2024-11-13 13:20:27 浏览: 21
创建一个简单的计算器实现加减法功能,可以使用面向对象编程的方式来设计,比如在Python中:
```python
class Calculator:
def __init__(self):
self.current_number = 0
def add(self, num):
"""
添加操作
:param num: 需要添加的数
:return: 当前数字加上num的结果
"""
self.current_number += num
return self.current_number
def subtract(self, num):
"""
减去操作
:param num: 需要从当前数字中减去的数
:return: 当前数字减去num的结果
"""
self.current_number -= num
return self.current_number
# 使用示例
calc = Calculator()
print(calc.add(5)) # 输出: 5 (因为初始值为0)
print(calc.subtract(2)) # 输出: 3
```
在这个例子中,`Calculator`类有两个方法:`add`用于加法,`subtract`用于减法。你可以通过实例化这个类并调用这些方法来进行计算。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)