有理数类

待写

在Python中,我们可以自定义一个有理数(Rational Number Class),通过继承内置的`numbers`模块中的` Rational`或直接创建一个来实现。下面是一个简单的例子,展示如何定义一个名为`CustomRational`的有理数: ```python from fractions import Fraction class CustomRational: def __init__(self, numerator, denominator): # 检查分母是否为0,避免除以零错误 if denominator == 0: raise ValueError("Denominator cannot be zero.") self.numerator = numerator self.denominator = abs(denominator) # 取绝对值以确保正数表示 def __add__(self, other): return CustomRational(self.numerator * other.denominator + other.numerator * self.denominator, self.denominator * other.denominator) def __sub__(self, other): return CustomRational(self.numerator * other.denominator - other.numerator * self.denominator, self.denominator * other.denominator) def __mul__(self, other): return CustomRational(self.numerator * other.numerator, self.denominator * other.denominator) def __truediv__(self, other): if isinstance(other, CustomRational): return CustomRational(self.numerator * other.denominator, self.denominator * other.numerator) else: return CustomRational(self.numerator * other, self.denominator) def __str__(self): return f"{self.numerator}/{self.denominator}" # 示例用法 r1 = CustomRational(4, 7) r2 = CustomRational(3, 5) print(r1 + r2) # 输出:(29/35) ``` 在这个`CustomRational`中,我们实现了加法 (`__add__`)、减法 (`__sub__`)、乘法 (`__mul__`) 和除法 (`__truediv__`) 这些基本操作,以及字符串转换 (`__str__`) 方法。用户可以创建这个的实例,并像处理标准的有理数一样使用它们。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值