我是python的新手,我仍然坚持如何让下面的代码在尝试划分2个分数时没有收到错误。
我收到的错误是" TypeError://不支持的操作数类型:' Fraction'和'分数'"
任何帮助都将不胜感激。
#Defining GCD to be used for all aspects below
def gcd(m,n):
while m%n != 0:
oldm = m
oldn = n
m = oldn
n = oldm%oldn
return n
#Begining of Fraction Function
class Fraction:
def __init__(self,top,bottom):
self.num = top
self.den = bottom
def __str__(self):
return str(self.num)+"/"+str(self.den)
def show(self):
print(self.num,"/",self.den)
def __add__(self,otherfraction): #Addition of Fractions
newnum = self.num*otherfraction.den + \
self.den*otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum,newden)
return Fraction(newnum//common,newden//common)
def __sub__(self,otherfraction): #Subtraction of Fractions
newnum = self.num*otherfraction.den - \
self.den*otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum,newden)
return Fraction(newnum//common,newden//common)
def __mul__(self,otherfraction): #Multiplication of Fractions
newnum = self.num*otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum,newden)
return Fraction(newnum//common,newden//common)
def __div__(self,otherfraction): #Division of Fractions
newnum = self.num*otherfraction.den
newden = self.den * otherfraction.num
common = gcd(newnum,newden)
return Fraction(newnum//common,newden//common)
def __eq__(self, other): #Equal Check
firstnum = self.num * other.den
secondnum = other.num * self.den
return firstnum == secondnum
def main():
x = Fraction(1,2)
y = Fraction(2,3)
#Printing of solutions
print("The fractions are:",x,"and",y)
print("Adding the fractions equals:",x+y)
print("Subtracting the fractions equals:",x-y)
print("Multiplying the fractions equals:",x*y)
print("Dividing the fractions equals:",x//y)
print("Fraction x is equal to fraction y: ", x == y)
main()