adding two fractions in python

前端 未结 3 1011
渐次进展
渐次进展 2020-12-21 08:38

I am trying to add two fractions in python

if input 1/4 + 1/4, I am expecting 1/2 result

I built a fraction class with an __add__ method for add

相关标签:
3条回答
  • 2020-12-21 09:00

    The general approach to simplifying fractions is to find the greatest common divisor of the numerator and denominator and then divide both of them by it

    0 讨论(0)
  • 2020-12-21 09:00

    This works :

    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)
    
        num=gcd(self.sumOfn,self.sumOfd)
    
        res_num=self.sumOfn/num
        res_den=self.sumOfd/num
    
        if res_num==res_den:print res_num
        else:print res_num,"/",res_den
    

    (fraction(1,4)+fraction(1,4))

    0 讨论(0)
  • 2020-12-21 09:05

    As mentioned by @icodez

    from fractions import Fraction
    print(Fraction(1,4)+Fraction(1,4))
    
    0 讨论(0)
提交回复
热议问题