Python小程序-寫一個計算一元二次方程的程序函數

題目要求:

請定義一個函數quadratic(a, b, c),接收3個參數,返回一元二次方程:ax^2 + bx + c = 0的兩個解。

程序代碼:

這只是一個函數,如果你不調用它的話,是不會產生任何輸出的。

import math
def quadratic(a, b, c):
    if not (isinstance(a,(int,float)) and isinstance(b,(int,float)) and isinstance(c,(int,float))):
        return '請輸入數字'
    else:
        d = -c + (b/2) ** 2
    if d < 0:
        return '無解'
    else:
        x1 = round((math.sqrt(d) - (b/2)) / a , 2)
        x2 = round((-math.sqrt(d) - (b/2)) / a , 2)
        return x1,x2

小結:

求數字的平方根可以使用math.sqrt()函數,需引入math模塊。

Leave a Reply

Your email address will not be published. Required fields are marked *

Captcha Code