【问题描述】 设计一个类,用自己的成员函数重载运算符,使对整型的运算符=、+、-、*、/ 适用于分数运算。要求: (1)输出结果是最简分数(可以是带分数); (2)分母为1,只输出分子。 参考的输入输出: Input x: 1/6 Input y: 2/9 x+y=7/18 x-y=-1/18 x*y=1/27 x/y=3/4 【输入形式】 提示“Input x: ”,输入第一个分数。如:1/6 提示“Input y: ”,输入第二个分数。如:2/9 【输出形式】 提示并输出+、-、*、/的结果,如 x+y=7/18 x-y=-1/18 x*y=1/27 x/y=3/4 【样例输入】 Input x: 1/6 Input y: 2/9 【样例输出】 x+y=7/18 x-y=-1/18 x*y=1/27 x/y=3/4写出这个问题的代码
时间: 2024-01-09 12:05:43 浏览: 75
20120805003罗晓峰
```python
class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
def __add__(self, other):
numerator = self.numerator * other.denominator + other.numerator * self.denominator
denominator = self.denominator * other.denominator
return Fraction.reduce_fraction(numerator, denominator)
def __sub__(self, other):
numerator = self.numerator * other.denominator - other.numerator * self.denominator
denominator = self.denominator * other.denominator
return Fraction.reduce_fraction(numerator, denominator)
def __mul__(self, other):
numerator = self.numerator * other.numerator
denominator = self.denominator * other.denominator
return Fraction.reduce_fraction(numerator, denominator)
def __truediv__(self, other):
numerator = self.numerator * other.denominator
denominator = self.denominator * other.numerator
return Fraction.reduce_fraction(numerator, denominator)
def __eq__(self, other):
return self.numerator * other.denominator == other.numerator * self.denominator
def __str__(self):
if self.denominator == 1:
return str(self.numerator)
elif self.numerator % self.denominator == 0:
return str(self.numerator // self.denominator)
else:
integer = self.numerator // self.denominator
numerator = self.numerator % self.denominator
denominator = self.denominator
return f"{integer} {numerator}/{denominator}"
@staticmethod
def gcd(a, b):
if b == 0:
return a
else:
return Fraction.gcd(b, a % b)
@staticmethod
def reduce_fraction(numerator, denominator):
gcd = Fraction.gcd(numerator, denominator)
numerator //= gcd
denominator //= gcd
return Fraction(numerator, denominator)
if __name__ == '__main__':
x_input = input("Input x: ")
x_numerator, x_denominator = map(int, x_input.split('/'))
x = Fraction(x_numerator, x_denominator)
y_input = input("Input y: ")
y_numerator, y_denominator = map(int, y_input.split('/'))
y = Fraction(y_numerator, y_denominator)
print(f"x+y={x + y}")
print(f"x-y={x - y}")
print(f"x*y={x * y}")
print(f"x/y={x / y}")
```
注:上述代码中,`__eq__` 方法重载了等于号运算符 `==`,用于判断两个分数是否相等。`__str__` 方法重载了字符串转换运算符 `str()`,用于将分数转换为字符串。
阅读全文