写出一段测试代码 在准备类Fraction时,创建一个类nul1denominatoreexception,它必须是一个检查异常,如果类Fraction的对象的分母为0,则抛出其实例。将Fraction类的各种方法完整呈现出来
时间: 2024-03-08 16:46:54 浏览: 51
测试用例设计.(null)
下面是一个例子,展示了如何在 Fraction 类中使用 NullDenominatorException:
```python
class NullDenominatorException(Exception):
pass
class Fraction:
def __init__(self, numerator, denominator):
if denominator == 0:
raise NullDenominatorException("分母不能为0")
self.numerator = numerator
self.denominator = denominator
def __str__(self):
return f"{self.numerator}/{self.denominator}"
def __add__(self, other):
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):
new_numerator = self.numerator * other.denominator - other.numerator * self.denominator
new_denominator = self.denominator * other.denominator
return Fraction(new_numerator, new_denominator)
def __mul__(self, other):
new_numerator = self.numerator * other.numerator
new_denominator = self.denominator * other.denominator
return Fraction(new_numerator, new_denominator)
def __truediv__(self, other):
new_numerator = self.numerator * other.denominator
new_denominator = self.denominator * other.numerator
return Fraction(new_numerator, new_denominator)
def simplify(self):
gcd = self._gcd(self.numerator, self.denominator)
self.numerator //= gcd
self.denominator //= gcd
@staticmethod
def _gcd(a, b):
if b == 0:
return a
return Fraction._gcd(b, a % b)
```
下面是一段测试代码:
```python
try:
# 创建一个分母为0的分数
f = Fraction(1, 0)
except NullDenominatorException as e:
print("发生异常:", e)
else:
print("分数为:", f)
# 创建两个分数
f1 = Fraction(1, 2)
f2 = Fraction(3, 4)
# 进行加法运算
f3 = f1 + f2
print(f"{f1} + {f2} = {f3}")
# 进行减法运算
f4 = f1 - f2
print(f"{f1} - {f2} = {f4}")
# 进行乘法运算
f5 = f1 * f2
print(f"{f1} * {f2} = {f5}")
# 进行除法运算
f6 = f1 / f2
print(f"{f1} / {f2} = {f6}")
# 简化分数
f7 = Fraction(2, 4)
print(f"原分数:{f7}")
f7.simplify()
print(f"简化后的分数:{f7}")
```
当分母为0时,运行上述代码会抛出 NullDenominatorException 异常。如果分母不为0,会进行加、减、乘、除、简化等运算,并输出结果。
阅读全文