编写一个分数类Fraction
时间: 2023-06-18 11:06:26 浏览: 118
好的,下面是一个简单的分数类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):
lcm = self.denominator * other.denominator // math.gcd(self.denominator, other.denominator)
numerator = (lcm // self.denominator) * self.numerator + (lcm // other.denominator) * other.numerator
return Fraction(numerator, lcm)
def __sub__(self, other):
lcm = self.denominator * other.denominator // math.gcd(self.denominator, other.denominator)
numerator = (lcm // self.denominator) * self.numerator - (lcm // other.denominator) * other.numerator
return Fraction(numerator, lcm)
def __mul__(self, other):
numerator = self.numerator * other.numerator
denominator = self.denominator * other.denominator
return Fraction(numerator, denominator)
def __truediv__(self, other):
numerator = self.numerator * other.denominator
denominator = self.denominator * other.numerator
return Fraction(numerator, denominator)
def simplify(self):
gcd = math.gcd(self.numerator, self.denominator)
self.numerator //= gcd
self.denominator //= gcd
def to_float(self):
return self.numerator / self.denominator
```
这个分数类支持分数的加减乘除和化简,并且可以将分数转换为浮点数。在初始化时需要提供分子和分母。可以使用 `__str__` 方法将分数转换为字符串形式输出,也可以使用 `simplify` 方法将分数化简。
阅读全文