📜  解决二次方程式的Python程序

📅  最后修改于: 2020-09-21 02:24:27             🧑  作者: Mango

当系数a,b和c已知时,此程序将计算二次方程式的根。

二次方程的标准形式为:

ax2 + bx + c = 0, where
a, b and c are real numbers and
a ≠ 0

源代码

# 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模块来执行复杂的平方根。首先,我们计算判别式,然后找到二次方程的两个解。

您可以在上述程序中更改abc的值并测试该程序。