Sunday, February 19, 2017

Write a JAVA program that display the roots of quadratic equation ax2+bx+c=0.

import java.util.Scanner;
public class Quadratic_Equation
{
    public static void main(String[] args)
      {
        int a, b, c;
        double root1, root2, d;
        Scanner s = new Scanner(System.in);
        System.out.println("Given quadratic equation:ax^2 + bx + c");
        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("Given quadratic equation:"+a+"x^2 + "+b+"x + "+c);
        d = b * b - 4 * a * c;
        if(d >= 0)
        {
            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
        {
            System.out.println("Roots are imaginary");
        }
    }
}
output:
>java Quadratic_Equation
Given quadratic equation:ax^2 + bx + c
Enter a:2
Enter b:4
Enter c:2
Given quadratic equation:2x^2 + 4x + 2
First root is:-1.0

Second root is:-1.0

No comments:

Post a Comment

Write a JAVA program to sort an array of Strings

import java.util.Scanner; public class SortStrings {     public static void main(String[] args)     {         int n;         String t...