Java教程

Java 求二次方程所有根的程序

寻找二次方程所有根的Java程序

在本程序中,您将学习找到二次方程的所有根并使用 Java 中的 format() 打印它们。
要理解此示例,您应该了解以下Java 编程主题:
Java if...else 语句 Java 数学 sqrt()
二次方程的标准形式是:
ax2 + bx + c = 0
这里, abc 是实数, a 不能等于0.
我们可以使用以下公式计算二次方的根:
x = (-b ± √(b2-4ac)) / (2a)
± 符号表示将有两个根:
root1 = (-b + √(b2-4ac)) / (2a)
root1 = (-b-√(b2-4ac)) / (2a)
b2-4ac 被称为二次方程的行列式。它指定了根的性质。也就是说,
如果行列式> 0,根是实数和不同的 如果行列式== 0,则根为实数且相等 如果行列式<0,则根复杂且不同

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

public class Main {
  public static void main(String[] args) {
    // value a, b, and c
    double a = 2.3, b = 4, c = 5.6;
    double root1, root2;
    // calculate the determinant (b2-4ac)
    double determinant = b * b-4 * a * c;
    // check if determinant is greater than 0
    if (determinant > 0) {
      // two real and distinct roots
      root1 = (-b + Math.sqrt(determinant)) / (2 * a);
      root2 = (-b-Math.sqrt(determinant)) / (2 * a);
      System.out.format("root1 = %.2f and root2 = %.2f", root1, root2);
    }
    // check if determinant is equal to 0
    else if (determinant == 0) {
      // two real and equal roots
      // determinant is equal to 0
      // so-b + 0 ==-b
      root1 = root2 =-b / (2 * a);
      System.out.format("root1 = root2 = %.2f;", root1);
    }
    // if determinant is less than zero
    else {
      // roots are complex number and distinct
      double real =-b / (2 * a);
      double imaginary = Math.sqrt(-determinant) / (2 * a);
      System.out.format("root1 = %.2f+%.2fi", real, imaginary);
      System.out.format("\nroot2 = %.2f-%.2fi", real, imaginary);
    }
  }
}
输出
root1 =-0.87+1.30i and root2 =-0.87-1.30i
在上述程序中,系数 ab、c分别设置为2.3、4和5.6、然后, 行列式计算为 b2 -4ac
根据行列式的值,按照上述公式计算根。请注意,我们使用了库函数 Math.sqrt() 来计算数字的平方根。
我们使用了 format() 方法来打印计算出的根。
format() 函数也可以用 printf() 替换为:
System.out.printf("root1 = root2 = %.2f;", root1);
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4