Processing math: 100%

Java程序用于求解一元二次方程的根


在本文中,我们将学习如何使用Java求解一元二次方程的根。一元二次方程的根由以下公式确定:

x=b±b24ac2a

在这里,我们将输入一元二次方程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,并将这些值存储起来。
  • 计算判别式:根据系数计算判别式,这有助于确定根的性质。
  • 检查判别式:如果判别式为正:计算并显示两个不同的实数根。
  • 如果判别式为零:计算并显示一个实数根,表明它是一个重复根。
  • 如果判别式为负:计算实部和虚部以指示复数根的存在,然后相应地显示它们。
  • 最后,关闭扫描器以释放资源。

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

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+浏览量

开启您的职业生涯

完成课程获得认证

开始学习
广告