[英]Why is my add function not giving me the correct output?
我試圖學習如何在 python 中創建類,我編寫了以下代碼來創建一個名為 fraction 的類。 但是,當我嘗試添加兩個分數時,我沒有得到正確的輸出。 有人能告訴我哪里可能出錯了嗎?
class fraction:
def __init__(self,top,bottom):
self.num=top
self.den=bottom
def show(self):
print(f"{self.num}/{self.den}")
def __str__(self):
return f"{self.num}/{self.den}"
def __add__(self,other_fraction):
new_num=self.num*other_fraction.den+self.den+other_fraction.num
new_den=self.den*other_fraction.den
return fraction(new_num,new_den)
我嘗試添加的分數是 1/4 和 2/4
print(fraction(1,4)+fraction(2,4))
我得到的輸出: 10/16
預期產出: 12/16
您有一個小錯字(應該是*
的+
)。
class Fraction:
def __init__(self, top, bottom):
self.num = top
self.den = bottom
def show(self):
print(self) # this automatically calls self.__str__()!
def __str__(self):
return f"{self.num}/{self.den}"
def __add__(self, other):
new_num = self.num * other.den + other.num * self.den
new_den = self.den * other.den
return Fraction(new_num, new_den)
(Fraction(1, 4) + Fraction(2, 4)).show() # 12/16
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.