我不知道我在做什么错我的__gt__
但我没有得到正确的结果。我尝试过改变事物,但我并不总是得到正确的打印输出。另外,我不太了解__radd__
或如何实施它。另外一个快速的问题是,当我打印出来的时候,有时我会得到像2 0/6这样的答案,我怎么才能打印出2呢?有人可以用我的__gt__帮助我,并帮助我使用__radd__?
这里是我的代码:
class Fraction:
def __init__(self,top,bottom):
self.num = top
self.den = bottom
self.gcd = gcd(self.num, self.den)
def __str__(self):
if self.den == 0:
return str(0)
elif self.num >= self.den:
if self.den == 1:
return str(self.num)
else:
return str(self.num // self.den)+\
' '+str(self.num%self.den)+\
'/'+str(self.den)
else:
return str(self.num)+"/"+str(self.den)
def show(self):
print(self.num,"/",self.den)
def __add__(self,otherfraction):
newnum = self.num*otherfraction.den + \
self.den*otherfraction.num
newden = self.den * otherfraction.den
common = self.gcd
return Fraction(newnum//common,newden//common)
def __sub__(self,otherfraction):
if self.den == 1:
sub = self.num - otherfraction.num
return sub
else:
newnum = self.num*otherfraction.den - \
self.den*otherfraction.num
newden = self.den * otherfraction.den
common = self.gcd
return Fraction(newnum//common,newden//common)
def __mul__(self,otherfraction):
newnum = self.num*otherfraction.num
newden = self.den * otherfraction.den
return Fraction(newnum//newnum,newden//newnum)
def __truediv__(self,otherfraction):
newnum = self.num*otherfraction.den
newden = self.den * otherfraction.num
common = self.gcd
return Fraction(newnum//common,newden//common)
def __gt__(self,other):
if self.den == 1:
if self.num > other.num:
return self.num
else:
frac1 = self.num*other.den
frac2 = self.den * other.num
if frac1 > frac2:
return self.num//self.den
else:
return other.num//other.den
def __radd__(self, other):
if other == 0:
return self
else:
return self.__add__(other)
def __eq__(self, other):
firstnum = self.num * other.den
secondnum = other.num * self.den
return firstnum == secondnum
def gcd(m,n):
while m%n != 0:
oldm = m
oldn = n
m = oldn
n = oldm%oldn
return n
def main():
getNum1 = int(input("Enter a numerator 1: "))
getDen1 = int(input("Enter a denominator 1: "))
getNum2 = int(input("Enter a numerator 2: "))
getDen2 = int(input("Enter a denominator 2: "))
f1 = Fraction(getNum1,getDen1)
f2 = Fraction(getNum2,getDen2)
print("[",f1,"]","[",f2,"]",sep='')
f3 = f1 + f2
print("Adding Fractions:",f3)
f3 = f1 - f2
print("Subtracting Fraction:",f3)
f3 = f1 * f2
print("Multiply Fraction:",f3)
f3 = f1/f2
print("Dividing Fraction:",f3)
if f1 > f2:
print(f1,"Greater than",f2)
else:
print(f2,"Greater than",f1)
if f1 == f2:
print("Fractions are equal")
else:
print("Fractions are not equal")
main()
预先感谢您的帮助!
你想用'__gt __()'方法实现什么?当'self'大于'other'时,你想返回true吗? –
是的,我只是试图让它返回自我,如果真或返回其他取决于哪一部分比另一部分大。 – keggy