使用Python建立一个分数类Rational,使之具有如下功能:能防止分母为0,当分数中不是最简形式时,进行约分以及避免分母为负数。用重载运算符完成分数的加、减、乘、除四则运算和大小的比较运算。
时间: 2024-05-05 21:16:17 浏览: 131
```python
class Rational:
def __init__(self, numerator=0, denominator=1):
if denominator == 0:
raise ValueError("Denominator cannot be zero.")
elif denominator < 0:
numerator *= -1
denominator *= -1
self.numerator = numerator
self.denominator = denominator
self.reduce()
def reduce(self):
gcd = self.calc_gcd(self.numerator, self.denominator)
self.numerator //= gcd
self.denominator //= gcd
def calc_gcd(self, a, b):
if b == 0:
return a
else:
return self.calc_gcd(b, a % b)
def __add__(self, other):
new_numerator = self.numerator * other.denominator + other.numerator * self.denominator
new_denominator = self.denominator * other.denominator
return Rational(new_numerator, new_denominator)
def __sub__(self, other):
new_numerator = self.numerator * other.denominator - other.numerator * self.denominator
new_denominator = self.denominator * other.denominator
return Rational(new_numerator, new_denominator)
def __mul__(self, other):
new_numerator = self.numerator * other.numerator
new_denominator = self.denominator * other.denominator
return Rational(new_numerator, new_denominator)
def __truediv__(self, other):
if other.numerator == 0:
raise ValueError("Cannot divide by zero.")
new_numerator = self.numerator * other.denominator
new_denominator = self.denominator * other.numerator
return Rational(new_numerator, new_denominator)
def __eq__(self, other):
return self.numerator == other.numerator and self.denominator == other.denominator
def __lt__(self, other):
return self.numerator * other.denominator < other.numerator * self.denominator
def __le__(self, other):
return self.numerator * other.denominator <= other.numerator * self.denominator
def __gt__(self, other):
return self.numerator * other.denominator > other.numerator * self.denominator
def __ge__(self, other):
return self.numerator * other.denominator >= other.numerator * self.denominator
def __str__(self):
if self.denominator == 1:
return str(self.numerator)
else:
return f"{self.numerator}/{self.denominator}"
```
使用示例:
```python
a = Rational(3, 4)
b = Rational(1, 2)
print(a + b) # 输出 5/4
print(a - b) # 输出 1/4
print(a * b) # 输出 3/8
print(a / b) # 输出 3/2
print(a == b) # 输出 False
print(a > b) # 输出 True
print(a >= b) # 输出 True
print(a < b) # 输出 False
print(a <= b) # 输出 False
```
阅读全文