2
我想在python添加兩個分數將在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,只是沒有簡化。我怎麼能解決這個問題?
的一般方法簡化分數是找到分子和分母的[最大公約數](http://en.wikipedia.org/wiki/Greatest_common_divisor),然後用它除以二者。 – 2015-04-03 02:15:14
'fractions'模塊已經有['Fraction'](https://docs.python.org/3/library/fractions.html#fractions.Fraction)類型。所有你需要的是'從分數導入分數'然後打印(分數(1,4)+分數(1,4))'。 – iCodez 2015-04-03 02:15:33
@AnthonySottile它的作品我建議你把下面的答案相同,我會選擇它作爲最佳答案 – Mozein 2015-04-03 02:37:55