设计一个名为“分数”的类 Fraction,包含分数的分子和分母(数据成员),以及分数之间的基本算术运算:加,减(成员方法),编写测试类,对给定的分数进行运算,并打印运算的结果
时间: 2023-06-05 15:08:28 浏览: 310
好的,我知道了。以下是设计的“分数”类Fraction和测试类的代码:
```
class Fraction:
def __init__(self, numer, denom):
self.numer = numer
self.denom = denom
def __add__(self, other):
new_numer = self.numer*other.denom + self.denom*other.numer
new_denom = self.denom*other.denom
return Fraction(new_numer, new_denom)
def __sub__(self, other):
new_numer = self.numer*other.denom - self.denom*other.numer
new_denom = self.denom*other.denom
return Fraction(new_numer, new_denom)
def __str__(self):
return str(self.numer) + "/" + str(self.denom)
if __name__ == "__main__":
f1 = Fraction(1, 2)
f2 = Fraction(1, 3)
print(f1 + f2)
print(f1 - f2)
```
测试结果如下:
```
5/6
1/6
```
希望这个答案能够帮到您,如果还有什么不懂的可以继续追问我。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)