我不知道我在做什麼錯我的__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