我正在撰寫一段代碼,其中有一個帶有屬性Numerator和Denominator的Fraction類。輸出應該以簡化的形式顯示分數。例如,20/100應該顯示為1/5。 我已經嘗試了下面的代碼,但是得到了一個型別錯誤,如下所示:
我不知道如何解決這個錯誤。請幫助我,因為我是Python的新手,希望建立強大的基礎知識。
uj5u.com熱心網友回復: 問題出在這個函式定義上: 在
標籤:TypeError
TypeError: unsupported operand type(s) for /: 'int'和'NoneType'。
類fraction。
def get_data(self):
self.__num=int(input("Enter the Nr:"))
self.__deno=int(input("Enter the Dr:"))
如果(self.__deno==0):
print("分數不可能")
退出()
def display_data(self):
self.__simplify()
print(self.__num,"/",self.__deno)
def __simplify(self):
print("簡化后的分數是" )
common_divisor=self.__GCD(self.__num,self.__deno)
self.__num=(self.__num)/(common_divisor)
self.__deno=(self.__deno)/(common_divisor)
def __GCD(self,a,b):
如果(b==0)。
回傳 a
否則。
self.__GCD(b,a%b)
f=fraction()
f.get_data()
f.display_data()
def __GCD(self,a,b):
如果(b==0)。
回傳a
否則。
self.__GCD(b,a%b)
else子句上沒有return陳述句。 (而且,else子句可以是implicit而不是explicit)。) 請嘗試:def __GCD(self, a, b):
如果b == 0。
回傳 a
回傳 self.__GCD(b, a % b)
