二次方程的标准形式是
ax2 + bx + c = 0, where a, b and c are real numbers and a ≠ 0
此二次方程的解由以下公式给出
(-b ± (b ** 2 - 4 * a * c) ** 0.5) / (2 * a)
源代码
# Solve the quadratic equation ax**2 + bx + c = 0
# import complex math module
import cmath
a = 1
b = 5
c = 6
# calculate the discriminant
d = (b**2) - (4*a*c)
# find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(sol1,sol2))
输出
Enter a: 1 Enter b: 5 Enter c: 6 The solutions are (-3+0j) and (-2+0j)
我们导入了 cmath
模块来执行复数平方根运算。首先,我们计算判别式,然后找出二次方程的两个解。
您可以在上面的程序中更改 a、b 和 c 的值并测试此程序。
另请阅读