私は新しいプログラミングで、この割り当てに少し困惑しています。2 つの分数のユーザー入力を取得して、積または商を取得することになっています。私たちは関数の定義を検討し、それらを完了しましたが、それらをユーザー入力に参照する方法とその逆の方法に困惑しています。ポインタや手がかりをいただければ幸いです。ある種のひらめきが必要だと思います。これが私の恥ずかしいコードです:
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)