为方程设计一个Equation类并测试
时间: 2024-02-24 21:00:00 浏览: 39
类设计简单测试题
好的,我可以为你设计一个Equation类并编写测试代码,如下所示:
```python
class Equation:
def __init__(self, a: float, b: float, c: float):
self.a = a
self.b = b
self.c = c
def solve(self):
delta = self.b * self.b - 4 * self.a * self.c
if delta < 0:
return None
elif delta == 0:
x = -self.b / (2 * self.a)
return x
else:
x1 = (-self.b + delta ** 0.5) / (2 * self.a)
x2 = (-self.b - delta ** 0.5) / (2 * self.a)
return (x1, x2)
# 测试代码
eq1 = Equation(1, -2, 1)
print("Equation:", eq1.a, "x^2 +", eq1.b, "x +", eq1.c, "= 0")
print("Roots:", eq1.solve())
eq2 = Equation(1, 2, 1)
print("Equation:", eq2.a, "x^2 +", eq2.b, "x +", eq2.c, "= 0")
print("Roots:", eq2.solve())
eq3 = Equation(2, 3, 1)
print("Equation:", eq3.a, "x^2 +", eq3.b, "x +", eq3.c, "= 0")
print("Roots:", eq3.solve())
```
运行结果如下:
```
Equation: 1 x^2 + -2 x + 1 = 0
Roots: 1.0
Equation: 1 x^2 + 2 x + 1 = 0
Roots: -1.0
Equation: 2 x^2 + 3 x + 1 = 0
Roots: (-0.5, -1.0)
```
测试代码首先创建了三个Equation对象,并分别传入不同的系数a、b、c。然后调用Equation类的solve方法求解方程的根,并打印了方程和根。结果与预期一致,验证了Equation类的基本功能。
阅读全文