定义一个有理数类。一个有理数类是一个可以表示成两个整数相除的数,如1/2、2/3、4/5。一个有理数类有两个整数成员表示:分子和分母。
时间: 2023-05-20 16:01:14 浏览: 162
好的,以下是一个简单的有理数类的定义:
```python
class Rational:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
def __str__(self):
return f"{self.numerator}/{self.denominator}"
def simplify(self):
gcd = self._gcd(self.numerator, self.denominator)
self.numerator //= gcd
self.denominator //= gcd
def _gcd(self, a, b):
if b == 0:
return a
return self._gcd(b, a % b)
def __add__(self, other):
numerator = self.numerator * other.denominator + other.numerator * self.denominator
denominator = self.denominator * other.denominator
return Rational(numerator, denominator)
def __sub__(self, other):
numerator = self.numerator * other.denominator - other.numerator * self.denominator
denominator = self.denominator * other.denominator
return Rational(numerator, denominator)
def __mul__(self, other):
numerator = self.numerator * other.numerator
denominator = self.denominator * other.denominator
return Rational(numerator, denominator)
def __truediv__(self, other):
numerator = self.numerator * other.denominator
denominator = self.denominator * other.numerator
return Rational(numerator, denominator)
```
这个类有两个成员变量:分子和分母。它还有一个 `__str__` 方法,用于将有理数转换为字符串。它还有一个 `simplify` 方法,用于将有理数化简为最简形式。它还有四个运算符重载方法:`__add__`、`__sub__`、`__mul__` 和 `__truediv__`,用于实现有理数的加、减、乘、除运算。
阅读全文