在python中添加两个分数 [英] adding two fractions in python

查看:60
本文介绍了在python中添加两个分数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 python 中添加两个分数

I am trying to add two fractions in python

如果输入 1/4 + 1/4,我期待 1/2 结果

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

我用一个 __add__ 加法方法构建了一个分数类

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

但是我得到 2,4 作为输出,实际上是 1/2,只是没有简化.我该如何解决这个问题?

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

推荐答案

简化分数的一般方法是找到 分子和分母的最大公约数,然后除以它

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

这篇关于在python中添加两个分数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆