C Program also avilable as C Program to Find Roots of a Quadratic Equation
import java.io.*;
class Quad
{
public static void main(String args[]) throws IOException
{
int a,b,c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a,b,c values: ");
a= Integer.parseInt(br.readLine());
b= Integer.parseInt(br.readLine());
c= Integer.parseInt(br.readLine());
if((a==0)&&(b==0)&&(c==0))
{
System.out.println("Enter atleast two non-zero co-efficients");
}
else
{
float r1=0,r2=0;
if(a==0)
{
r1= (float)-c/b;
System.out.println("The roots are:"+r1);
}
else
{
float d=(b*b)-(4*a*c);
if(d<0)
{
System.out.println("Roots are imaginary");
float real=(float)(-b)/(2*a);
float img=(float)(Math.sqrt(Math.abs(d)))/(2*a);
System.out.println("r1="+real+"+i"+img);
System.out.println("r2="+real+"-i"+img);
}
else
{
r1=(float)(-b+Math.sqrt(d))/(2*a);
r2=(float)(-b-Math.sqrt(d))/(2*a);
if(d==0)
{
System.out.println("Roots are real and equal");
}
else
{
System.out.println("Roots are real and different");
}
System.out.println("r1="+r1);
System.out.println("r2="+r2);
}
}
}
}
}
OUTPUT:
Enter a,b,c values: 1 4 1 Roots are real and different r1= -0.2679492 r2= -3.732051