系统提供的答案有问题
# Enter a code
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
class Rational(object):
def __init__(self, p, q):
self.p = p
self.q = q
def __add__(self, r):
return Rational(self.p * r.q + self.q * r.p, self.q * r.q)
def __sub__(self, r):
return Rational(self.p * r.q - self.q * r.p, self.q * r.q)
def __mul__(self, r):
return Rational(self.p * r.p, self.q * r.q)
def __truediv__(self, r):
return Rational(self.p * r.q, self.q * r.p)
def __str__(self):
g = gcd(self.p, self.q)
return '{}/{}'.format(int(self.p/g), int(self.q/g))
r1 = Rational(1, 2)
r2 = Rational(1, 5)
print(r1 + r2)
print(r1 - r2)
print(r1 * r2)
print(r1 / r2)
上面是系统提供的答案,但是提交后运行报错,请问原因是啥,以下是运行结果
Traceback (most recent call last): File "index.py", line 28, in print(r1 / r2) TypeError: unsupported operand type(s) for /: 'Rational' and 'Rational' 7/10 3/10 1/10