In this java program, you’ll learn how to find all the roots of a quadratic equation and print them using format()
in Java.
In algebra, a quadratic equation is an equation that can be rearranged in standard form as
ax²+bx+c = 0
where x represents an unknown, and a, b, and c represent known numbers, where a ≠ 0. If a = 0, then the equation is linear, not quadratic, as there is no ax2 term. The numbers a, b, and c are the coefficients of the equation and may be distinguished by calling them, respectively, the quadratic coefficient, the linear coefficient, and the constant or free term.
A Quadratic Equation has at most two solutions, and they depend entirely upon the discriminant.
//Java Program to Find all Roots of a Quadratic Equation
import java.util.Scanner;
public class JavaPrograms {
public static void main(String[] args) {
double secondRoot = 0, firstRoot = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the value of a :");
double a = scanner.nextDouble();
System.out.println("Enter the value of b :");
double b = scanner.nextDouble();
System.out.println("Enter the value of c :");
double c = scanner.nextDouble();
scanner.close();
double determinant = (b * b) - (4 * a * c);
// check if determinant is greater than 0
if (determinant > 0) {
// two real and distinct roots
firstRoot = (-b + Math.sqrt(determinant)) / (2 * a);
secondRoot = (-b - Math.sqrt(determinant)) / (2 * a);
System.out.format("root1 = %.2f and root2 = %.2f", firstRoot, secondRoot);
}
// 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
firstRoot = secondRoot = -b / (2 * a);
System.out.format("root1 = root2 = %.2f;", firstRoot);
}
// 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);
}
}
}
Enter the value of a :
5
Enter the value of b :
5
Enter the value of c :
8
root1 = -0.50+1.16i
root2 = -0.50-1.16i
Comments