Java程式用於求解一元二次方程的根


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

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

在這裡,我們將輸入一元二次方程ax2 + bx + c = 0的係數a、b和c的值。程式將根據判別式(b2 - 4ac)的值確定根的性質。如果判別式大於零,則有兩個不同的實數根;如果等於零,則只有一個實數根。

問題陳述

編寫一個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物件來讀取使用者輸入的值,並提示使用者輸入一元二次方程的係數a、b和c,並將這些值儲存起來。
  • 計算判別式:根據係數計算判別式,這有助於確定根的性質。
  • 檢查判別式:如果判別式為正:計算並顯示兩個不同的實數根。
  • 如果判別式為零:計算並顯示一個實數根,表明它是一個重複根。
  • 如果判別式為負:計算實部和虛部以指示覆數根的存在,然後相應地顯示它們。
  • 最後,關閉掃描器以釋放資源。

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

程式碼解釋

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

更新於:2024年10月21日

13K+瀏覽量

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告