请利用phython编写函数solve-quadratic(a,b,c)求解一元二次方程ax²+bx+c,并添加至少三个测试用例
时间: 2024-11-30 09:28:35 浏览: 19
要编写一个名为`solve_quadratic`的函数来解决一元二次方程`ax² + bx + c = 0`,可以使用公式`(-b ± sqrt(b² - 4ac)) / (2a)`。以下是函数定义及其测试用例的示例:
```python
import math
def solve_quadratic(a, b, c):
discriminant = b**2 - 4*a*c
if discriminant > 0:
root1 = (-b + math.sqrt(discriminant)) / (2 * a)
root2 = (-b - math.sqrt(discriminant)) / (2 * a)
return (root1, root2)
elif discriminant == 0:
root = -b / (2 * a)
return (root,)
else:
return "No real roots"
# 测试用例
test_cases = [
(1, 2, 1), # 应该有两个实根(-1, -1)
(1, 0, 1), # 应该只有一个实根(-1)
(1, -3, 2), # 应该有两个虚根(复数解)
(0, 0, 0), # 特殊情况,应返回0
]
for a, b, c in test_cases:
result = solve_quadratic(a, b, c)
print(f"Given equation {a}x^2 + {b}x + {c} has roots:", result)
```
阅读全文