系統(tǒng)提供的答案有問題
# 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)
上面是系統(tǒng)提供的答案,但是提交后運行報錯,請問原因是啥,以下是運行結(jié)果
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
2023-12-12
7/10
3/10
1/10
5/2
[Done] exited with code=0 in 0.069 seconds
沒問題啊,可以正常運行,你復(fù)制的時候漏了啥吧