Java Program to Find Quadratic Equation

Solve quadratic equation in java. A quadratic equation is a second-degree equation, meaning it contains at least one squared element. ax2 + bx + c = 0 is the conventional form, with a, b, and c being numerical coefficients and x being an unknown variable.

import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
double a = sc.nextDouble();
double b = sc.nextDouble();
double c = sc.nextDouble();
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 and root2 = %.2f-%.2fi", real, img, real, img);
}
}
}

Output:

45
34
56
root1 = -0.38+1.05i and root2 = -0.38-1.05i