作为一个项目,我正在从头开始创建一个 Rational 类,它可以将两个分数作为输入并存储简化的分数。但是,当我尝试输入两个分数时,它似乎隐式使用整数除法,所以我根本无法存储/操作分数。我是否错误地解决了这个问题?错误在哪里?
示例:Rational(3/2,9/2) 返回 (1,4) 而不是 (1/3)。
def gcd(numerator,denominator):
if numerator < 0:
absNum = -numerator
elif denominator < 0:
absDen = -denominator
else:
absNum = numerator
absDen = denominator
while absNum != absDen:
if absNum > absDen:
absNum = absNum - absDen
elif absDen >= absNum:
absDen = absDen - absNum
return(absNum)
class Rational:
def __init__(self,numerator=0,denominator=1):
self.numerator = numerator
self.denominator = denominator
if denominator == 0:
raise ZeroDivisionError("Error: cannot store number with 0 in denominator.")
elif denominator < 0:
if numerator < 0:
self.denominator = -denominator
self.numerator = -numerator
else:
self.numerator = numerator
self.denominator = -denominator
if numerator != 0:
com = gcd(numerator,denominator)
numerator = numerator/com
denominator = denominator/com
self.numerator = numerator
self.denominator = denominator
Rational(5/3,8/3)
返回 (1,2) 而不是 (5,8) 应该的。编辑:后半部分:我希望能够输入 Rational(Rational(5/3),Rational(8/3)) 和 (5,8) 结果。这似乎与上面的略有不同。