求解一元二次方程 ax^2 + bx + c = 0 (输入a,b,c的值,求解方程。a != 0,结果保留4位小数)用python语言
时间: 2024-09-24 20:21:05 浏览: 45
在Python中,可以使用math库中的sqrt函数和复数功能来求解一元二次方程ax² + bx + c = 0,其中a不等于0。这里是一个简单的实现:
```python
import cmath
def solve_quadratic_equation(a, b, c):
# 计算判别式
discriminant = (b**2) - (4*a*c)
# 如果判别式大于0,有两个实根
if discriminant > 0:
x1 = (-b + cmath.sqrt(discriminant)) / (2 * a)
x2 = (-b - cmath.sqrt(discriminant)) / (2 * a)
return round(x1.real, 4), round(x2.real, 4)
# 判别式等于0,有一个实根
elif discriminant == 0:
x = -b / (2 * a)
return round(x, 4)
# 判别式小于0,有两个复根
else:
real_part = -b / (2 * a)
imaginary_part = cmath.sqrt(-discriminant) / (2 * a)
return round(real_part, 4), round(imaginary_part, 4)
# 输入系数
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]}")
阅读全文