python实现关于一元二次方程的公式求解的所有情况 (包括不同实根、相同实根、共钜复根)
时间: 2023-05-14 22:05:18 浏览: 219
Python编程实现数学运算求一元二次方程的实根算法示例
5星 · 资源好评率100%
以下是 Python 实现一元二次方程的公式求解的所有情况的代码:
```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, 3)) # 共轭复根:x1 = -1.0+1.4142135623730951i, x2 = -1.0-1.4142135623730951i
```
希望这个代码能够帮助你解决问题!
阅读全文