Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
715 views
in Technique[技术] by (71.8m points)

adding two fractions in python

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 addition

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))

However I am getting 2,4 as output, which is actually 1/2, just not simplified. How could I fix that problem ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As mentioned by @icodez

from fractions import Fraction
print(Fraction(1,4)+Fraction(1,4))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...