编写代码实现假分数加减乘除运算
时间: 2024-06-11 14:06:52 浏览: 147
下面是 Python 代码实现假分数加减乘除运算的示例:
```python
class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
self.reduce()
def __str__(self):
return f"{self.numerator}/{self.denominator}"
def reduce(self):
gcd = self.get_gcd(self.numerator, self.denominator)
self.numerator //= gcd
self.denominator //= gcd
def get_gcd(self, a, b):
while b:
a, b = b, a % b
return a
def get_lcm(self, a, b):
return a * b // self.get_gcd(a, b)
def __add__(self, other):
lcm = self.get_lcm(self.denominator, other.denominator)
numerator = self.numerator * lcm // self.denominator + other.numerator * lcm // other.denominator
denominator = lcm
return Fraction(numerator, denominator)
def __sub__(self, other):
lcm = self.get_lcm(self.denominator, other.denominator)
numerator = self.numerator * lcm // self.denominator - other.numerator * lcm // other.denominator
denominator = lcm
return Fraction(numerator, denominator)
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)
```
使用示例:
```python
f1 = Fraction(3, 4)
f2 = Fraction(2, 5)
print(f1 + f2) # 输出 23/20
print(f1 - f2) # 输出 7/20
print(f1 * f2) # 输出 3/10
print(f1 / f2) # 输出 15/8
```
阅读全文