问答详情
源自:4-4 Python类的数学运算

系统提供的答案有问题

# 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

提问者:慕斯卡6411321 2023-11-23 16:34

个回答

  • 時頌望見
    2023-12-12 22:34:33

    7/10

    3/10

    1/10

    5/2


    [Done] exited with code=0 in 0.069 seconds

    没问题啊,可以正常运行,你复制的时候漏了啥吧