Python 二次方程

Document 對象參考手冊 Python3 實(shí)例

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

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

# Filename : test.py
# author by : www.o2fo.com

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

# 導(dǎo)入 cmath(復(fù)雜數(shù)學(xué)運(yùn)算) 模塊
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('結(jié)果為 {0} 和 {1}'.format(sol1,sol2))

執(zhí)行以上代碼輸出結(jié)果為:

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

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

Document 對象參考手冊 Python3 實(shí)例