在python中添加两个分数
发布时间:2020-12-20 11:41:53 所属栏目:Python 来源:网络整理
导读:我想在 python中添加两个分数 如果输入1/4 1/4,我期待1/2结果 我用__add__方法构建了一个分数类来添加 from fractions import gcdclass fraction: def __init__(self,numerator,denominator): self.num = numerator self.deno = denominator def __add__(sel
我想在
python中添加两个分数
如果输入1/4 1/4,我期待1/2结果 我用__add__方法构建了一个分数类来添加 from fractions import gcd class fraction: def __init__(self,numerator,denominator): self.num = numerator self.deno = denominator def __add__(self,other): self.sumOfn = self.num + other.num self.sumOfd = gcd(self.deno,other.deno) return(self.sumOfn,self.sumOfd) print(fraction(1,4)+fraction(1,4)) 但是我的输出为2,4,实际上是1/2,只是没有简化.我怎么能解决这个问题? 解决方法
简化分数的一般方法是找到分子和分母的
greatest common divisor,然后将它们除以它们
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |