Write a java program that display the roots of a quadratic equation ax2+bx=0. Calculate the discriminate D and basing on value of D, describe the nature of root.

 import java.util.Scanner;


public class QuadraticEquation {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        

        System.out.println("Enter the values of a and b for the equation ax^2 + bx = 0:");

        

        System.out.print("Enter a: ");

        double a = scanner.nextDouble();

        

        System.out.print("Enter b: ");

        double b = scanner.nextDouble();

        

        // Calculate discriminant

        double D = b * b - 4 * a * 0; // Discriminant D = b^2 - 4ac (for the equation ax^2 + bx + c = 0, here c = 0)

        

        System.out.println("\nDiscriminant D = " + D);

        

        if (D > 0) {

            double root1 = (-b + Math.sqrt(D)) / (2 * a);

            double root2 = (-b - Math.sqrt(D)) / (2 * a);

            System.out.println("Roots are real and different.");

            System.out.println("Root 1 = " + root1);

            System.out.println("Root 2 = " + root2);

        } else if (D == 0) {

            double root = -b / (2 * a);

            System.out.println("Roots are real and equal.");

            System.out.println("Root = " + root);

        } else {

            System.out.println("Roots are complex (not real).");

        }

        

        scanner.close();

    }

}

Output:


Comments