二次方程式 ax**2 + bx + c = 0(用python實現,區分實數根與複數根)

import math
import cmath

def sol(a,b,c):
    #判斷b的平方是否大於4ac,大於等於的時候是實數根,小於的時候是複數根(cmath相比與math的區別是cmath是複數運算)
    if b**2 >= 4*a*c :
        sqrt = math.sqrt(b**2 - 4*a*c)
        x1 = (-b + sqrt) / (2 * a)
        x2 = (-b - sqrt) / (2 * a)
        print("第一個根是:", x1)
        print("第二個根是:", x2)
    else:
        sqrt = cmath.sqrt(b**2 - 4 * a * c)
        x1 = (-b + sqrt) / (2 * a)
        x2 = (-b - sqrt) / (2 * a)
        #複數格式化輸出實數+複數小數點後三位
        print("第一個根是{0}+{1:0.3f}j".format(x1.real, x1.imag))
        print("第二個根是{0}+{1:0.3f}j".format(x2.real, x2.imag))

if __name__ == '__main__':

    a = float(input("請輸入第一個參數"))
    b = float(input("請輸入第二個參數"))
    c = float(input("請輸入第三個參數"))
    sol(a,b,c)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章