python中计算带分数_带分数的Python用户输入

我是新编程的,在这项任务上我有点左右为难。我们需要用户输入两个分数,然后得到乘积或商。我们讨论了定义函数,我已经完成了,但是我不知道如何将它们引用到用户输入,反之亦然。任何提示或线索都将不胜感激,我只需要一些顿悟。这是我的尴尬代码: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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值