Roots of Quadratic Equation
Find the roots of a quadratic equation ax^2 + bx + c = 0 using discriminant.
IntermediateTopic: Module 2: Conditional Programs
Java Roots of Quadratic Equation Program
This program helps you to learn the fundamental structure and syntax of Java programming.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a: ");
double a = sc.nextDouble();
System.out.print("Enter b: ");
double b = sc.nextDouble();
System.out.print("Enter c: ");
double c = sc.nextDouble();
double d = b * b - 4 * a * c;
if (d > 0) {
double r1 = (-b + Math.sqrt(d)) / (2 * a);
double r2 = (-b - Math.sqrt(d)) / (2 * a);
System.out.println("Two real and distinct roots: " + r1 + " and " + r2);
} else if (d == 0) {
double r = -b / (2 * a);
System.out.println("Two equal real roots: " + r + " and " + r);
} else {
double real = -b / (2 * a);
double imag = Math.sqrt(-d) / (2 * a);
System.out.println("Complex roots: " + real + " + " + imag + "i and " + real + " - " + imag + "i");
}
sc.close();
}
}Output
Enter a: 1 Enter b: -3 Enter c: 2 Two real and distinct roots: 2.0 and 1.0
Understanding Roots of Quadratic Equation
We use discriminant d = b² - 4ac to decide if roots are real distinct, real equal, or complex.
Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.