编写一个分数类Fraction
时间: 2023-08-14 22:07:22 浏览: 184
好的,以下是一个简单的分数类 `Fraction` 的实现:
```python
class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
def __str__(self):
return f"{self.numerator}/{self.denominator}"
def __add__(self, other):
if self.denominator == other.denominator:
return Fraction(self.numerator + other.numerator, self.denominator)
else:
common_denominator = self.denominator * other.denominator
new_numerator1 = self.numerator * other.denominator
new_numerator2 = other.numerator * self.denominator
new_numerator = new_numerator1 + new_numerator2
return Fraction(new_numerator, common_denominator)
def __sub__(self, other):
if self.denominator == other.denominator:
return Fraction(self.numerator - other.numerator, self.denominator)
else:
common_denominator = self.denominator * other.denominator
new_numerator1 = self.numerator * other.denominator
new_numerator2 = other.numerator * self.denominator
new_numerator = new_numerator1 - new_numerator2
return Fraction(new_numerator, common_denominator)
def __mul__(self, other):
new_numerator = self.numerator * other.numerator
new_denominator = self.denominator * other.denominator
return Fraction(new_numerator, new_denominator)
def __truediv__(self, other):
new_numerator = self.numerator * other.denominator
new_denominator = self.denominator * other.numerator
return Fraction(new_numerator, new_denominator)
```
这个类有一个构造函数 `__init__`,接受分子和分母作为参数,并将它们存储在实例变量 `numerator` 和 `denominator` 中。`__str__` 方法返回可读的字符串,表示这个分数。
这个类还重载了运算符 `+`、`-`、`*` 和 `/`,可以进行分数的加减乘除运算。在计算加减法时,如果分母不同,则需要先通分。在计算除法时,需要将第二个分数取倒数,然后再将两个分数相乘。
阅读全文