python求一元二次方程式ax2+bx+c=0的根。a,b,c的值在运行时由键盘输入,它们的值满足b2-4*a*c>=0
时间: 2024-11-05 22:30:24 浏览: 12
在Python中,你可以通过使用数学库`cmath`来处理复数解的情况,并利用公式法求解一元二次方程ax^2 + bx + c = 0。当判别式b^2 - 4ac大于等于0时,这意味着方程有实数解。以下是一个简单的函数示例:
```python
import cmath
def solve_quadratic_equation(a, b, c):
discriminant = b**2 - 4*a*c
if discriminant >= 0:
# 实数解
x1 = (-b + cmath.sqrt(discriminant)) / (2 * a)
x2 = (-b - cmath.sqrt(discriminant)) / (2 * a)
else:
# 复数解
real_part = -b / (2 * a)
imaginary_part = cmath.sqrt(-discriminant) / (2 * a)
x1 = complex(real_part, imaginary_part)
x2 = complex(real_part, -imaginary_part)
return x1, x2
# 获取用户输入
a = float(input("请输入a的值: "))
b = float(input("请输入b的值: "))
c = float(input("请输入c的值: "))
# 解方程并打印结果
solution = solve_quadratic_equation(a, b, c)
print(f"方程的解是: {solution[0]}, {solution[1]}")
阅读全文