Thursday, August 21, 2014

Quadratic

Class Name: Quadratic. Create a program to find the roots of a quadratic equation using the formula, d=b2-4*a*c. Note that for any negative value in d, there is no root available. If value is equal to 0, roots are equal. Use the formula r=-b/(2*a) in getting the roots. Otherwise, real roots can be derived by getting the square root of d, then use this r=-b+d/(2*a). Then, Display the roots.

______________________________________________________________

import java.util.Scanner;
public class Quadratic {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
       
        double a=0;
        double b=0;
        double c=0;
        double d=0;
        double r=0;
        double r2=0;
       
        System.out.print("This program finds the roots of a quadratic equation.");
        System.out.print("\nEnter first value [a]: ");
        a=input.nextDouble();
        System.out.print("Enter second value [b]: ");
        b=input.nextDouble();
        System.out.print("Enter first value [c]: ");
        c=input.nextDouble();
       
        d=(b*b)-4*(a*c);
        r=b/(2*a);
        r2=-b+d/(2*a);
       
        if (d<0){System.out.print("No roots.");}
        else if (d==0){System.out.print("Roots are equal: "+r);}
        else System.out.print("Roots: "+r+ " & "+r2);
    }
}

No comments:

Post a Comment

advertisement