Roots of Quadratic Equation in Java
Find the roots of a quadratic equation ax^2 + bx + c = 0 using discriminant.
IntermediateModule 2: Conditional ProgramsExample 14 of 20
roots-of-quadratic-equation.java
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);67 System.out.print("Enter a: ");8 double a = sc.nextDouble();9 System.out.print("Enter b: ");10 double b = sc.nextDouble();11 System.out.print("Enter c: ");12 double c = sc.nextDouble();1314 double d = b * b - 4 * a * c;1516 if (d > 0) {17 double r1 = (-b + Math.sqrt(d)) / (2 * a);18 double r2 = (-b - Math.sqrt(d)) / (2 * a);19 System.out.println("Two real and distinct roots: " + r1 + " and " + r2);20 } else if (d == 0) {21 double r = -b / (2 * a);22 System.out.println("Two equal real roots: " + r + " and " + r);23 } else {24 double real = -b / (2 * a);25 double imag = Math.sqrt(-d) / (2 * a);26 System.out.println("Complex roots: " + real + " + " + imag + "i and " + real + " - " + imag + "i");27 }2829 sc.close();30 }31}
Output
Enter a: 1 Enter b: -3 Enter c: 2 Two real and distinct roots: 2.0 and 1.0
What's going on
We use discriminant d = b² - 4ac to decide if roots are real distinct, real equal, or complex.