當系數(shù)a,b和c已知時,此程序將計算二次方程的根。
要理解此示例,您應該了解以下Python編程主題:
二次方程的標準形式為:
ax2 + bx + c = 0, where a, b and c are real numbers and a ≠ 0
# 解二次方程 ax**2 + bx + c = 0 # 導入復雜數(shù)學模塊 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執(zhí)行復雜平方根的模塊。首先,我們計算判別式,然后找到二次方程的兩個解。
你可以改變的價值a,b并c在上面的程序和測試這個程序。