建立一个分数类fraction,用于表示最简分数
时间: 2023-08-16 07:05:54 浏览: 162
定义和使用分数类fraction
3星 · 编辑精心推荐
好的,以下是一个简单的分数类Fraction的实现,可以表示最简分数:
```python
class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
self.reduce()
def reduce(self):
# 求最大公因数
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
# 化简分数
if self.denominator == 0:
raise ZeroDivisionError("denominator cannot be zero")
if self.numerator == 0:
self.denominator = 1
else:
common = gcd(self.numerator, self.denominator)
self.numerator //= common
self.denominator //= common
def __str__(self):
if self.denominator == 1:
return str(self.numerator)
return f"{self.numerator}/{self.denominator}"
def __add__(self, other):
if isinstance(other, Fraction):
numerator = self.numerator * other.denominator + self.denominator * other.numerator
denominator = self.denominator * other.denominator
return Fraction(numerator, denominator)
else:
raise TypeError("unsupported operand type(s) for +: 'Fraction' and '{type(other).__name__}'")
def __sub__(self, other):
if isinstance(other, Fraction):
numerator = self.numerator * other.denominator - self.denominator * other.numerator
denominator = self.denominator * other.denominator
return Fraction(numerator, denominator)
else:
raise TypeError("unsupported operand type(s) for -: 'Fraction' and '{type(other).__name__}'")
def __mul__(self, other):
if isinstance(other, Fraction):
numerator = self.numerator * other.numerator
denominator = self.denominator * other.denominator
return Fraction(numerator, denominator)
else:
raise TypeError("unsupported operand type(s) for *: 'Fraction' and '{type(other).__name__}'")
def __truediv__(self, other):
if isinstance(other, Fraction):
numerator = self.numerator * other.denominator
denominator = self.denominator * other.numerator
return Fraction(numerator, denominator)
else:
raise TypeError("unsupported operand type(s) for /: 'Fraction' and '{type(other).__name__}'")
```
这个类包含了分数的四则运算,其中使用了递归求最大公因数的方法对分数进行化简。可以通过以下方式使用:
```python
# 创建分数对象
f1 = Fraction(2, 6)
f2 = Fraction(3, 4)
# 打印分数
print(f1) # 1/3
print(f2) # 3/4
# 分数加法
print(f1 + f2) # 17/12
# 分数减法
print(f1 - f2) # -5/12
# 分数乘法
print(f1 * f2) # 1/2
# 分数除法
print(f1 / f2) # 2/9
```
阅读全文