# 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
7/10
3/10
1/10
5/2
[Done] exited with code=0 in 0.069 seconds
没问题啊,可以正常运行,你复制的时候漏了啥吧