设计一个表示分数的类Fraction。这个类用两个int类型的变量分别表示分子和分母。注意,在创建和做完运算后应该化简分数为最简形式。如2/4应该被化简为1/2。
时间: 2024-05-13 13:17:24 浏览: 127
好的,以下是Fraction类的代码实现:
```python
class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
self.reduce()
def __str__(self):
return str(self.numerator) + '/' + str(self.denominator)
def reduce(self):
gcd = self.gcd(self.numerator, self.denominator)
self.numerator //= gcd
self.denominator //= gcd
def gcd(self, a, b):
if b == 0:
return a
else:
return self.gcd(b, a % b)
def __add__(self, other):
new_numer = self.numerator * other.denominator + other.numerator * self.denominator
new_denom = self.denominator * other.denominator
return Fraction(new_numer, new_denom)
def __sub__(self, other):
new_numer = self.numerator * other.denominator - other.numerator * self.denominator
new_denom = self.denominator * other.denominator
return Fraction(new_numer, new_denom)
def __mul__(self, other):
new_numer = self.numerator * other.numerator
new_denom = self.denominator * other.denominator
return Fraction(new_numer, new_denom)
def __truediv__(self, other):
new_numer = self.numerator * other.denominator
new_denom = self.denominator * other.numerator
return Fraction(new_numer, new_denom)
```
这个类有一个构造函数,以及__str__方法重载了打印输出的行为,便于观察结果。reduce方法用于将分数化为最简形式。gcd方法用于求分子和分母的最大公约数,方便化简分数。加、减、乘、除操作都被重载了。
阅读全文