Java Program to Find the Roots of a Quadratic Equation using sqrt() Function
ADVERTISEMENTS
Java program to find the roots of a quadratic equation using Math.sqrt() function. In this article, you will learn how to find the roots of a quadratic equation in java language using Math.sqrt() function.
What is the Quadratic equation?
ax2 + bx + c = 0
where a, b and c these are the real numbers & a != 0
where a, b and c these are the real numbers & a != 0
Source Code
// Java Program to Find the Roots of a Quadratic Equation using sqrt() Function
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double p, q, r, d, r1, r2, rp, ip;
// p, q and r - To store the real numbers
// d - To store the discriminant
// r1 - To store the first root
// r2 - To store the second root
// rp - To store the real part
// ip - To store the image part
System.out.println ("-----Enter the these coefficients a, b and c----");
p = in.nextFloat();
q = in.nextFloat();
r = in.nextFloat();
d = q * q - 4 * p * r;
if (d > 0) {
// It is the condition for real and different roots
r1 = (-q + Math.sqrt(d)) / (2 * p);
r2 = (-q - Math.sqrt(d)) / (2 * p);
System.out.println ("\nThe r1 = " + r1 + " & r2 = " + r2);
} else if (d == 0) {
// It is the condition for real and equal roots
r1 = r2 = -q / (2 * p);
System.out.println ("\nThe r1 = r2 = " + r1 + ";");
} else {
// if the roots are not real number
rp = -q / (2 * p);
ip = Math.sqrt(-d) / (2 * p);
System.out.printf ("\nThe r1 = %.2f+%.2fi & r2 = %.2f-%.2fi\n", rp, ip, rp, ip);
}
}
}
Output
-----Enter the these coefficients a, b and c----
7.8
5.3
6.2
The r1 = -0.34+0.82i & r2 = -0.34-0.82i