编写程序实现关于一元二次方程的公式求解的所有情况(包括不同实根、相同实根、共轭复根)。
时间: 2023-05-16 16:06:04 浏览: 73
好的,以下是一个实现一元二次方程求解的程序:
```python
import math
def solve_quadratic_equation(a, b, c):
delta = b**2 - 4*a*c
if delta > 0:
x1 = (-b + math.sqrt(delta)) / (2*a)
x2 = (-b - math.sqrt(delta)) / (2*a)
return "两个实根分别为:x1 = {}, x2 = {}".format(x1, x2)
elif delta == 0:
x = -b / (2*a)
return "一个实根为:x = {}".format(x)
else:
real_part = -b / (2*a)
imag_part = math.sqrt(-delta) / (2*a)
return "共轭复根为:x1 = {}+{}i, x2 = {}-{}i".format(real_part, imag_part, real_part, imag_part)
# 测试
print(solve_quadratic_equation(1, 2, 1)) # 一个实根为:x = -1.0
print(solve_quadratic_equation(1, -3, 2)) # 两个实根分别为:x1 = 2.0, x2 = 1.0
print(solve_quadratic_equation(1, 2, 2)) # 共轭复根为:x1 = -1.0+1.0i, x2 = -1.0-1.0i
```
希望这个程序能够帮到你!
阅读全文