Write a program to find all roots of a quadratic equation.


The program first declares three variables a, b, and c representing the coefficients of the quadratic equation. Then, it calculates the discriminant of the equation using the formula b^2 - 4ac.

Next, the program uses if statements to determine the type of roots the quadratic equation has based on the value of the discriminant. If the discriminant is greater than 0, the program calculates the two roots using the quadratic formula (-b ± sqrt(b^2 - 4ac)) / (2a) and prints them. If the discriminant is equal to 0, the program calculates the single root (-b / 2a) and prints it twice. If the discriminant is less than 0, the program calculates the two complex roots of the equation and prints them in the format of (real part + imaginary part i) and (real part - imaginary part i).

It is important to note that this program uses hardcoded values for a, b, and c. In order to find the roots of a specific quadratic equation, the values of a, b, and c would need to be input by the user using the Scanner class or obtained from some other source.

Source Code

import java.util.Scanner;
class Find_Roots
{
	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;
		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);
		}
		else if (determinant == 0) {	
		  root1 = root2 = -b / (2 * a);
		  System.out.format("root1 = root2 = %.2f;", root1);
		}
		else {
 
		  double real = -b / (2 * a);
		  double img = Math.sqrt(-determinant) / (2 * a);
		  System.out.format("root1 = %.2f+%.2fi", real, img);
		  System.out.format("\nroot2 = %.2f-%.2fi", real, img);
		}
	}
}

Output

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

Example Programs