Wednesday, 19 December 2012

Aim: To write a Java program that prints all real solutions to the quadratic equation ax2+bx+c=0. Read in a, b, c and use the quadratic formula. If the discriminant b2 -4ac is negative, display a message stating that there are no real solutions.


import java.io.*;
class Quadratic
{
  public static void main(String args[])throws IOException
  {
  int a,b,c,disc;
 double x1,x2;
InputStreamReader obj=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(obj);
System.out.println("enter a,b,c values");
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
c=Integer.parseInt(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");
  }
}

No comments:

Post a Comment