0% found this document useful (0 votes)
62 views

Java Program To Find All Roots of A Quadratic Equation

This Java program calculates the roots of a quadratic equation. It takes in coefficients a, b, and c, calculates the determinant, and uses the determinant value to determine if there are two real roots, two equal real roots, or two complex roots. It then outputs the calculated roots formatted to two decimal places.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views

Java Program To Find All Roots of A Quadratic Equation

This Java program calculates the roots of a quadratic equation. It takes in coefficients a, b, and c, calculates the determinant, and uses the determinant value to determine if there are two real roots, two equal real roots, or two complex roots. It then outputs the calculated roots formatted to two decimal places.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Example: Java Program to Find Roots of a Quadratic Equation

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);

Output

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

In the above program, the coefficients a , b, and c are set to 2.3, 4, and 5.6
respectively. Then, the determinant is calculated as b2 - 4ac .

Based on the value of the determinant, the roots are calculated as given in the formula
above. Notice we've used library function Math.sqrt() to calculate the square root of a
number.
We have used the format() method to print the calculated roots.

The format() function can also be replaced by printf() as:

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

You might also like