Python 二次方程

Document 對象參考手冊 Python3 實例

以下實例為通過用戶輸入數字,并計算二次方程:

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.w3cschool.cn

# 二次方程式 ax**2 + bx + c = 0
# a、b、c 用戶提供

# 導入 cmath(復雜數學運算) 模塊
import cmath

a = float(input('輸入 a: '))
b = float(input('輸入 b: '))
c = float(input('輸入 c: '))

# 計算
d = (b**2) - (4*a*c)

# 兩種求解方式
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)

print('結果為 {0} 和 {1}'.format(sol1,sol2))

執行以上代碼輸出結果為:

$ python test.py 
輸入 a: 1
輸入 b: 5
輸入 c: 6
結果為 (-3+0j) 和 (-2+0j)

該實例中,我們使用了 cmath (complex math) 模塊的 sqrt() 方法 來計算平方根。

Document 對象參考手冊 Python3 實例