Java程式查詢二次方程的根


在本文中,我們將學習如何使用Java查詢二次方程的根。二次方程的根由以下公式確定

$$x = \frac{-b\pm\sqrt[]{b^2-4ac}}{2a}$$

這裡我們將輸入二次方程𝑎 𝑥 2 + 𝑏 𝑥 + 𝑐 = 0的係數𝑎、𝑏和𝑐的值。程式將根據判別式( 𝑏 2 − 4 𝑎 𝑐 )的值確定根的性質。如果判別式大於零,則有兩個不同的根;如果等於零,則正好有一個根。

問題陳述

編寫一個Java程式來查詢二次方程的根。

輸入

Enter the value of a ::
15
Enter the value of b ::
68
Enter the value of c ::
3

輸出

Roots are :: -0.044555558333472335 and -4.488777774999861

計算二次方程根的步驟

以下是計算二次方程根的步驟:

  • 首先從java.util包中匯入Scanner類
  • 定義包含main方法的類,並宣告兩個根firstRoot和secondRoot的變數來儲存結果。
  • 例項化一個Scanner物件以讀取使用者輸入的值,並提示使用者輸入二次方程的係數𝑎、𝑏和𝑐,並將這些值儲存起來。
  • 計算判別式:根據係數計算判別式,這有助於確定根的性質。
  • 檢查判別式:如果判別式為正:計算並顯示兩個不同的實根。
  • 如果判別式為零:確定並顯示一個實根,表示它是一個重複根。
  • 如果判別式為負:計算實部和虛部以指示覆根的存在,然後相應地顯示它們。
  • 最後,關閉掃描器以釋放資源。

Java程式查詢二次方程的根

以下是一個在Java程式設計中查詢二次方程根的示例:

import java.util.Scanner;

public class RootsOfQuadraticEquation {
    public static void main(String args[]) {
        double secondRoot = 0, firstRoot = 0;
        Scanner sc = new Scanner(System.in);
        
        System.out.println("Enter the value of a ::");
        double a = sc.nextDouble();

        System.out.println("Enter the value of b ::");
        double b = sc.nextDouble();

        System.out.println("Enter the value of c ::");
        double c = sc.nextDouble();

        // Calculate the determinant
        double determinant = (b * b) - (4 * a * c);

        // Check the value of the determinant
        if (determinant > 0) {
            double sqrt = Math.sqrt(determinant);
            firstRoot = (-b + sqrt) / (2 * a);
            secondRoot = (-b - sqrt) / (2 * a);
            System.out.println("Roots are :: " + firstRoot + " and " + secondRoot);
        } else if (determinant == 0) {
            firstRoot = (-b) / (2 * a);
            System.out.println("Root is :: " + firstRoot);
        } else {
            // If the determinant is negative, calculate complex roots
            double realPart = -b / (2 * a);
            double imaginaryPart = Math.sqrt(-determinant) / (2 * a);
            System.out.println("Roots are complex: " + realPart + " + " + imaginaryPart + "i and " + realPart + " - " + imaginaryPart + "i");
        }

        // Close the scanner
        sc.close();
    }
}

輸出

Enter the value of a ::
15
Enter the value of b ::
68
Enter the value of c ::
3
Roots are :: -0.044555558333472335 and -4.488777774999861

程式碼解釋

在程式中,我們將獲取使用者輸入方程𝑎𝑥2+𝑏𝑥+𝑐=0的係數𝑎、𝑏和𝑐。然後,它使用公式𝑏2−4𝑎𝑐計算判別式。根據判別式的值,程式確定方程是否有兩個不同的根、一個根或沒有實根。如果判別式大於零,則程式使用二次公式計算並顯示兩個實根。如果判別式等於零,則計算並列印單個根。如果判別式為負,則告知使用者沒有實根。

更新於: 2024年10月21日

13K+ 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.