m0_57743728 2021-05-14 15:34 采纳率: 0%
浏览 4

[Python] 请问这个程序设计里面怎么确保分子分母的因数只有1呀~ Design a class

[Python] 请问这个程序设计里面怎么确保分子分母的因数只有1呀~ Design a class ‘fractions’ so that the fractions can be directly added and subtracted like integers. For example, 2/1+3/5=13/5, and make sure that the numerator and denominator do not have a common factor greater than 1.(hint: overwrite __str__, __add__, __sub__ methods)……
  • 写回答

1条回答 默认 最新

  • ARMFUN 2024-06-21 19:35
    关注

    按照以下步骤进行实现:

    定义 fractions 类。
    重写 str 方法以便能够打印分数。
    重写 addsub 方法以便能够进行分数的加法和减法操作。
    确保分子和分母在每次操作后都被约分(即分子和分母没有大于1的公因数)。
    以下是完整的 Python 实现:

    import math
    
    class Fraction:
        def __init__(self, numerator, denominator):
            if denominator == 0:
                raise ValueError("Denominator cannot be zero")
            self.numerator = numerator
            self.denominator = denominator
            self.simplify()
        
        def simplify(self):
            """Simplify the fraction by dividing both numerator and denominator by their GCD."""
            gcd = math.gcd(self.numerator, self.denominator)
            self.numerator //= gcd
            self.denominator //= gcd
        
        def __str__(self):
            return f"{self.numerator}/{self.denominator}"
        
        def __add__(self, other):
            if not isinstance(other, Fraction):
                return NotImplemented
            new_numerator = self.numerator * other.denominator + other.numerator * self.denominator
            new_denominator = self.denominator * other.denominator
            return Fraction(new_numerator, new_denominator)
        
        def __sub__(self, other):
            if not isinstance(other, Fraction):
                return NotImplemented
            new_numerator = self.numerator * other.denominator - other.numerator * self.denominator
            new_denominator = self.denominator * other.denominator
            return Fraction(new_numerator, new_denominator)
        
        def __eq__(self, other):
            if not isinstance(other, Fraction):
                return NotImplemented
            return (self.numerator == other.numerator) and (self.denominator == other.denominator)
    
    # Example usage
    frac1 = Fraction(2, 1)
    frac2 = Fraction(3, 5)
    print(f"{frac1} + {frac2} = {frac1 + frac2}")
    print(f"{frac1} - {frac2} = {frac1 - frac2}")
    
    
    

    详细说明
    初始化 init 方法:定义分子和分母,并确保分母不为零。然后调用 simplify 方法对分数进行约分。
    约分 simplify 方法:使用 math.gcd 函数计算分子和分母的最大公约数(GCD),并用它们分别除以这个GCD,以达到约分的效果。
    打印 str 方法:返回分数的字符串表示形式。
    加法 add 方法:重载加法操作符,计算新分数的分子和分母,并返回一个新的 Fraction 对象。
    减法 sub 方法:重载减法操作符,计算新分数的分子和分母,并返回一个新的 Fraction 对象。
    等于 eq 方法:重载等于操作符,检查两个分数是否相等。
    这样,你就可以创建 Fraction 对象,并直接使用 + 和 - 操作符进行加减操作,同时确保结果是简化过的分数。

    评论

报告相同问题?