Python 程序:求解二次方程式
当系数 a,b 和 c 已知时,此程序将计算二次方程的根。
要理解此示例,您应该了解以下 [Python 编程]( "Python tutorial")主题:
二次方程的标准形式为:
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模块以执行复数平方根。 首先,我们计算判别式,然后找到二次方程的两个解。
您可以在上述程序中更改a,b和c的值并测试该程序。