Roots of Quadratic Equation

Find the roots of a quadratic equation ax^2 + bx + c = 0 using discriminant.

JavaIntermediate
Java
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

We use discriminant d = b² - 4ac to decide if roots are real distinct, real equal, or complex.