如何简化我班上的分数?

2024-09-22 16:35:13 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的Fraction类的代码:

class Fraction:
    """Class for performing fraction arithmetic.
    Each Fraction has two attributes: a numerator, n and a deconominator, d.
    Both must be integer and the deonominator cannot be zero.
    """
    def __init__(self,n,d):
        """Performs error checking and standardises to ensure denominator is positive"""
        if type(n)!=int or type(d)!=int:
            raise TypeError("n and d must be integers")
        if d==0:
            raise ValueError("d must be positive")
        elif d<0:
            self.n = -n
            self.d = -d
        else:
            self.n = n
            self.d = d

    def __str__(self):
        """Gives string representation of Fraction (so we can use print)"""
        return(str(self.n) + "/" + str(self.d))

    def __add__(self, otherFrac):
        """Produces new Fraction for the sum of two Fractions"""
        newN = self.n*otherFrac.d + self.d*otherFrac.n
        newD = self.d*otherFrac.d
        newFrac = Fraction(newN, newD)
        return(newFrac)

    def __sub__(self, otherFrac):
        """Produces new Fraction for the difference between two Fractions"""
        newN = self.n*otherFrac.d - self.d*otherFrac.n
        newD = self.d*otherFrac.d
        newFrac = Fraction(newN, newD)
        return(newFrac)

    def __mul__(self, otherFrac):
        """Produces new Fraction for the product of two Fractions"""
        newN = self.n*otherFrac.n
        newD = self.d*otherFrac.d
        newFrac = Fraction(newN, newD)
        return(newFrac)

    def __truediv__(self, otherFrac):
        """Produces new Fraction for the quotient of two Fractions"""
        newN = self.n*otherFrac.d
        newD = self.d*otherFrac.n
        newFrac = Fraction(newN, newD)
        return(newFrac)

    def __eq__(self,otherFrac):
        return(self.n * otherFrac.d) == (self.d * otherFrac.n)

为了使这门课更有用,我如何简化分数?在

例如:我想把30/15改成5/3?看起来是:
(30/2)/(18/2)-->;15/9----->;(15/3)/(9/3)--->;5/3

我不使用import fraction。在


Tags: andoftheselfforreturndefbe
1条回答
网友
1楼 · 发布于 2024-09-22 16:35:13

你想找到分子和分母的最大公约数,然后除以。^{} function在Python的标准库中,但您可能希望自己实现它。找到它的一个著名的(并且易于实现)算法称为Euclid's algorithm。在

你可以实现欧几里得的算法,把你的两个数相减得到第三个数(差),然后丢弃三个数中最大的一个数,重复这个减法/丢弃过程,直到其中一个数为零。在

顺便说一下,减半30/15是2/1。在

以你为例(30/15)

30-15=15

现在你有3个数字(30,15,15)。丢弃最大的,然后重复。在

15-15=0

现在有3个更小的数字(15,15,0)。在

15-0=15

因为这并没有改变数字集,你可以得出结论,15是你最大的公约数。(如果你把30和15除以15,得到2和1,这就是你的约化分数的分子和分母。在

相关问题 更多 >