Find The Roots Of A Quadratic Equation | Java Programs

Output:

*** Roots Of Quadratic Equation ***

Enter a: 2
Enter b: 9
Enter c: 3

Given quadratic equation: 2x^2 + 9x + 3

Roots are real and unequal
First root is  :  -0.36254139118231254
Second root is : -4.1374586088176875

Click Here For Java Online Compiler

Solution:

import java.util.Scanner;

public class RootsOfEquation {

    public static void main(String[] args) {
        int a, b, c;
        double root1, root2, d;
        Scanner s = new Scanner(System.in);
        System.out.println("*** Roots Of Quadratic Equation ***" + "\n");
        System.out.print("Enter a: ");
        a = s.nextInt();
        System.out.print("Enter b: ");
        b = s.nextInt();
        System.out.print("Enter c: ");
        c = s.nextInt();
        System.out.println();
        System.out.println("Given quadratic equation: " + a + "x^2 + " + b + "x + " + c);
        System.out.println();
        d = b * b - 4 * a * c;
        if (d > 0) {
            System.out.println("Roots are real and unequal");
            root1 = (-b + Math.sqrt(d)) / (2 * a);
            root2 = (-b - Math.sqrt(d)) / (2 * a);
            System.out.println("First root is  :  " + root1);
            System.out.println("Second root is : " + root2);
        } else if (d == 0) {
            System.out.println("Roots are real and equal");
            root1 = (-b + Math.sqrt(d)) / (2 * a);
            System.out.println("Root:" + root1);
        } else {
            System.out.println("Roots are imaginary");
        }
    }
}
Share This :

Related Post



sentiment_satisfied Emoticon