Write a C program to compute roots of quadratic equation

04 a] Write a C program to compute the roots of a quadratic equation by accepting the coefficients and printing the appropriate message along with the values.

Answer:-

#include<stdio.h>
#include<math.h>
void main()
{
float x1, x2, a, b, c, disc;
printf("Enter the coefficients a, b and c\n");
scanf("%f%f%f",&a,&b,&c);
disc=(b*b)-(4*a*c);
if(disc == 0)
{
x1= -b/(2*a);
x2= -b/(2*a);
printf("The roots are real and equal\n");
printf("1st root = %f\n",x1);
printf("2nd root = %f\n",x2);
}
else if(disc > 0)
{
x1=(-b+sqrt(disc))/(2*a);
x2=(-b-sqrt(disc))/(2*a);
printf("The roots are real and distinct\n");
printf("1st root = %f\n",x1);
printf("2nd root = %f\n",x2);
}
else
{
x1=-b/(2*a);
x2=sqrt(fabs(disc))/(2*a);
printf("The roots are imaginary\n");
printf("1st root = %f + i%f\n",x1,x2);
printf("2nd root = %f - i%f\n",x1,x2);
}
}
Output

Enter the coefficients a, b and c 
1 2 3
The roots are imaginary
1st root = -1.000000 + i1.414214
2nd root = -1.000000 - i1.414214

Enter the coefficients a, b and c 
4 4 1
The roots are real and equal
1st root = -0.500000
2nd root = -0.500000

Enter the coefficients a, b and c 
3 6 2
The roots are real and distinct
1st root = -0.422650
2nd root = -1.577350

Leave a Reply

Your email address will not be published. Required fields are marked *