Java program to find all roots of a quadratic equation

www.‮i‬giftidea.com

Here's a Java program to find all roots of a quadratic equation:

import java.util.Scanner;

public class QuadraticEquation {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the value of a: ");
        double a = scanner.nextDouble();

        System.out.print("Enter the value of b: ");
        double b = scanner.nextDouble();

        System.out.print("Enter the value of c: ");
        double c = scanner.nextDouble();

        double discriminant = b * b - 4 * a * c;

        if (discriminant > 0) {
            double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
            double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
            System.out.println("The roots are " + root1 + " and " + root2);
        } else if (discriminant == 0) {
            double root = -b / (2 * a);
            System.out.println("The root is " + root);
        } else {
            double realPart = -b / (2 * a);
            double imaginaryPart = Math.sqrt(-discriminant) / (2 * a);
            System.out.println("The roots are " + realPart + " + " + imaginaryPart + "i and " + realPart + " - " + imaginaryPart + "i");
        }
    }
}

This program takes input from the user for the coefficients a, b, and c of the quadratic equation ax^2 + bx + c = 0. It then calculates the discriminant using the formula b^2 - 4ac, and determines the number and type of roots based on the discriminant value. If the discriminant is positive, there are two real roots, which are calculated using the quadratic formula. If the discriminant is zero, there is one real root. If the discriminant is negative, there are two complex roots, which are calculated using the quadratic formula for complex numbers. The program then prints the roots to the console.