
当系数a,b和c已知时,此程序将计算二次方程的根。
要理解此示例,您应该了解以下Python编程主题:
二次方程的标准形式为:
ax2 + bx + c = 0, where a, b and c are real numbers and a ≠ 0
源代码
# 解二次方程 ax**2 + bx + c = 0
# 导入复杂数学模块
import cmath
a = 1
b = 5
c = 6
# 计算判别式
d = (b**2) - (4*a*c)
# 两个解决方案
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在上面的程序和测试这个程序。
