print the roots of a quadratic equation ax2+bx=0 in Java Program


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.

Source Code : 



  
  import java.io.*; 
  
  class Quadratic { 

    public static void main(String args[]) throws IOException {
    
        double x1,x2,disc,a,b,c; 
        InputStreamReader obj=new InputStreamReader(System.in); 
        BufferedReader br=new BufferedReader(obj); 

        System.out.println("enter a,b,c values"); 
        a=Double.parseDouble(br.readLine()); 
        b=Double.parseDouble(br.readLine()); 
        c=Double.parseDouble(br.readLine()); 
        disc= (b*b)-(4*a*c); 

        if (disc==0) { 
            System.out.println("roots are real and equal "); 
            x1=x2=b/(2*a); 
            System.out.println("roots are "+x1+","+x2); 
        } 
        else if(disc>0) { 
            System.out.println("roots are real and unequal"); 
            x1=(-b+Math.sqrt(disc))/(2*a); 
            x2=(b+Math.sqrt(disc))/(2*a); 
            System.out.println("roots are "+x1+","+x2); 
        } 
        else { 

            System.out.println("roots are imaginary");

        }
    }
}


 

Output :

enter a,b,c values 1 2 1 roots are real and equal roots are 1.0,1.0


output image














Post a Comment

0 Comments

Close Menu