TQC+ 程式語言 Python 3 _ 506 一元二次方程式

說明:
請撰寫一程式,將使用者輸入的三個整數(代表一元二次方程式 \( ax^2 + bx + c = 0\) 的三個係數a、b、c)作為參數傳遞給一個名為compute()的函式,該函式回傳方程式的解,如無解則輸出【Your equation has no root.】
提示:輸出有順序性

範例輸入1:
2
-3
1
範例輸出1:
1.0, 0.5
範例輸入2:
9
9
8
範例輸出2:
Your equation has no root.
程式碼:
def compute(a, b, c):
    y = (b**2) - (4 * a * c)

    if y > 0:
        x1, x2 = (-b + (y**0.5)) / (2 * a), (-b - (y**0.5)) / (2 * a)
        return x1, x2
    else:
        return 'Your equation has no root.', None

a = eval( input() )
b = eval( input() )
c = eval( input() )
m, n = compute( a , b , c )

if n == None:
    print(m)
else:
    print('{}, {}'.format(m, n))

沒有留言:

張貼留言