编写一个Python程序,计算一元二次方程的根(包括复数根)
时间: 2024-05-09 19:18:35 浏览: 81
```
import math
def quadratic(a, b, c):
delta = b * b - 4 * a * c
if delta < 0:
realPart = -b / (2 * a)
imagPart = math.sqrt(-delta) / (2 * a)
print("该方程有两个复数根:")
print("x1 = ", realPart, "+", imagPart, "i")
print("x2 = ", realPart, "-", imagPart, "i")
elif delta == 0:
x = -b / (2 * a)
print("该方程有一个实根:")
print("x = ", x)
else:
x1 = (-b + math.sqrt(delta)) / (2 * a)
x2 = (-b - math.sqrt(delta)) / (2 * a)
print("该方程有两个实根:")
print("x1 = ", x1)
print("x2 = ", x2)
# 测试
quadratic(1, -2, 1) # delta = 0,有一个实根,x = 1.0
quadratic(1, 2, 1) # delta = 0,有一个实根,x = -1.0
quadratic(1, 1, 1) # delta < 0,有两个复数根,x1 = -0.5 + 0.8660254037844386i,x2 = -0.5 - 0.8660254037844386i
quadratic(1, -5, 6) # delta > 0,有两个实根,x1 = 3.0,x2 = 2.0
```
阅读全文