Skip to content

Latest commit

 

History

History
76 lines (52 loc) · 2.31 KB

File metadata and controls

76 lines (52 loc) · 2.31 KB

Java 程序:查找二次方程式的所有根

原文: https://www.programiz.com/java-programming/examples/quadratic-roots-equation

在该程序中,您将学习查找二次方程式的所有根,并使用 Java 中的format()打印它们。

二次方程的标准形式为:

ax2 + bx + c = 0, where
a, b and c are real numbers and
a0

术语b<sup>2</sup>-4ac被称为二次方程的行列式。 行列式说明了根的性质。

  • 如果行列式大于 0,则根是实数且不同。
  • 如果行列式等于 0,则根是实数且相等。
  • 如果行列式小于 0,则根是复数且不同。

示例:查找二次方程式根的 Java 程序

public class Quadratic {

    public static void main(String[] args) {

        double a = 2.3, b = 4, c = 5.6;
        double root1, root2;

        double determinant = b * b - 4 * a * c;

        // condition for real and different roots
        if(determinant > 0) {
            root1 = (-b + Math.sqrt(determinant)) / (2 * a);
            root2 = (-b - Math.sqrt(determinant)) / (2 * a);

            System.out.format("root1 = %.2f and root2 = %.2f", root1 , root2);
        }
        // Condition for real and equal roots
        else if(determinant == 0) {
            root1 = root2 = -b / (2 * a);

            System.out.format("root1 = root2 = %.2f;", root1);
        }
        // If roots are not real
        else {
            double realPart = -b / (2 *a);
            double imaginaryPart = Math.sqrt(-determinant) / (2 * a);

            System.out.format("root1 = %.2f+%.2fi and root2 = %.2f-%.2fi", realPart, imaginaryPart, realPart, imaginaryPart);
        }
    }
}

运行该程序时,输出为:

root1 = -0.87+1.30i and root2 = -0.87-1.30i

在上述程序中,系数abc分别设置为 2.3、4 和 5.6。 然后,将determinant计算为b^2 - 4ac

根据行列式的值,根的计算公式如上式所示。 注意,我们已经使用库函数Math.sqrt()计算数字的平方根。

使用 Java 中的format()函数将计算出的根(实数根或复数根)打印在屏幕上。format()函数也可以由printf()替换为:

System.out.printf("root1 = root2 = %.2f;", root1);