我是新编程,我对这个任务有点难过。我们应该接受用户输入的两个分数并获得产品或商。我们重新定义了函数,我已经完成了这些,但我对如何将它们引用到用户输入和反之亦然感到困惑。任何指针或线索将不胜感激,我认为我只需要某种顿悟。这是我尴尬的代码:
import fractions
def gcd(m,n):
while m%n != 0: #finds the GCD (global definition)
oldm = m
oldn = n
m = oldn
n = oldm%oldn
return n
class Fraction:
def __init__(self,top,bottom): #constructor; creating fraction
self.num = top #methods to go about placing numerator and denominator
self.den = bottom
def __str__(self): #calling the fraction from methods above
return str(self.num)+"/"+str(self.den) #Returns the value of fraction
def __add__(self,otherfraction): #For addition of fractions (self = first fraction, otherfraction = second fraction)
newnum = self.num*otherfraction.den + self.den*otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum,newden)
return Fraction(newnum//common,newden//common) #Returns the new fraction with reduced answer.
def __mul__(self,otherfraction): #For multiplication of fractions
newnum = self.num*otherfraction.num
newden = self.den*otherfraction.den
common = gcd(newnum,newden)
return Fraction(newnum//common,newden//common)
def __floordiv__(self,otherfraction): #For division of fractions; use // not /
newnum = self.num*otherfraction.den #Use multiplication of the reciprocal
newden = self.den*otherfraction.num
common = gcd(newnum,newden)
return Fraction(newnum//common,newden//common)
def __sub__(self,otherfraction): #For 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)