📜  什么是分数?(1)

📅  最后修改于: 2023-12-03 14:49:11.419000             🧑  作者: Mango

什么是分数?

分数是数学中常见的一种数值表示方法。它表示整数部分和分数部分的比例关系,通常写成“分子/分母”的形式。

在程序中,我们可以用分数类来表示分数。下面是一个示例代码片段:

class Fraction:
    def __init__(self, numerator, denominator):
        self.numerator = numerator
        self.denominator = denominator
        
    def __str__(self):
        return str(self.numerator) + "/" + str(self.denominator)
        
    def __add__(self, other):
        new_numerator = self.numerator * other.denominator + self.denominator * other.numerator
        new_denominator = self.denominator * other.denominator
        common_divisor = self.gcd(new_numerator, new_denominator)
        return Fraction(new_numerator // common_divisor, new_denominator // common_divisor)
        
    def __sub__(self, other):
        new_numerator = self.numerator * other.denominator - self.denominator * other.numerator
        new_denominator = self.denominator * other.denominator
        common_divisor = self.gcd(new_numerator, new_denominator)
        return Fraction(new_numerator // common_divisor, new_denominator // common_divisor)
        
    def __mul__(self, other):
        new_numerator = self.numerator * other.numerator
        new_denominator = self.denominator * other.denominator
        common_divisor = self.gcd(new_numerator, new_denominator)
        return Fraction(new_numerator // common_divisor, new_denominator // common_divisor)
        
    def __truediv__(self, other):
        new_numerator = self.numerator * other.denominator
        new_denominator = self.denominator * other.numerator
        common_divisor = self.gcd(new_numerator, new_denominator)
        return Fraction(new_numerator // common_divisor, new_denominator // common_divisor)
        
    def __eq__(self, other):
        return self.numerator == other.numerator and self.denominator == other.denominator
        
    def gcd(self, a, b):
        if b == 0:
            return a
        else:
            return self.gcd(b, a % b)

这个分数类可以进行四则运算和比较运算,并且会对结果进行约分。使用这个类可以轻松处理分数的运算问题。