Skip to content

Python 506 一元二次方程式

Python TQC

題目說明:

請撰寫一程式,將使用者輸入的三個整數(代表一元二次方程式\(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.

範例輸入3

1
2
1

範例輸出3

-1.0

題目解析

問題分析:

這個問題要求我們寫一個程式,接收三個整數作為參數,這三個整數分別代表一元二次方程式的三個係數 \(a\)\(b\)\(c\)。然後將這些參數傳遞給名為 compute() 的函式,該函式應該回傳方程式的解,如果無解則輸出 “Your equation has no root.”。

解題思路:

  1. 定義一個函式 compute(a, b, c)
  2. compute() 函式中,先檢查判別式 \(b^2 - 4ac\) 是否大於或等於零,如果是,代表方程式有實數解,計算出解 \(x_1\)\(x_2\),並返回它們。
  3. 如果判別式小於零,代表方程式無實數解,返回 0 以表示無解。
  4. 在主程式中,接收使用者輸入的三個整數 \(a\)\(b\)\(c\)
  5. 將接收到的參數傳遞給 compute() 函式。
  6. 根據 compute() 函式的返回值,輸出方程式的解或 “Your equation has no root.”。

思考方向:

  1. 確保理解一元二次方程式的求解方法,特別是判別式的概念。
  2. 在實作時需要考慮方程式有零、一個或兩個解的情況。
  3. 確保處理輸入的資料型態,以及輸出的格式。

Solution

import math
def compute(a, b, c):
    if b ** 2 - 4 * a * c >= 0:
        ans1 = (-b + math.sqrt(b ** 2 - 4 * a * c)) / (2 * a)
        ans2 = (-b - math.sqrt(b ** 2 - 4 * a * c)) / (2 * a)
        return ans1, ans2
    else:
        return 0    
a = eval(input())
b = eval(input())
c = eval(input())
if compute(a, b, c) != 0:
    ans1, ans2 = compute(a, b, c)
    if ans1 != ans2:
        print('{}, {}' .format(ans1, ans2))
    else:
        print('{}'.format(ans1))
else:
    print('Your equation has no root.')
def compute(a, b, c):
    if b ** 2 - 4 * a * c >= 0:
        ans1 = (-b + (b ** 2 - 4 * a * c)**0.5) / (2 * a)
        ans2 = (-b - (b ** 2 - 4 * a * c)**0.5) / (2 * a)
        if ans1 != ans2:
            print('{}, {}' .format(ans1, ans2))
        else:
            print('{}'.format(ans1))
    else:
    print('Your equation has no root.')
compute(eval(input()), eval(input()), eval(input()))

Last update : 13 novembre 2024
Created : 13 novembre 2024

Comments

Comments