C Program to Solve Quadratic Equations along with Types of Root
Program
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a, b, c, d, r1, r2, rp, ip;
clrscr();
printf("Enter coefficients a, b and c: \n");
scanf("%f%f%f", &a, &b, &c);
d = b*b - 4*a*c;
if( d == 0)
{
r1 = -b / (2*a);
r2 = r1;
printf("Roots are real and equal.\n");
printf("Root1 = %f\n", r1);
printf("Root2 = %f", r2);
}
else if(d > 0)
{
r1 = (-b + sqrt(d))/ (2*a);
r2 = ( -b - sqrt(d))/(2*a);
printf("Roots are real and unequal.\n");
printf("Root1 = %f\n", r1);
printf("Root2 = %f", r2);
}
else
{
rp = -b/(2*a);
ip = sqrt(-d)/(2*a);
printf("Roots are Imaginary.\n");
printf("Root1 = %f + %f i\n", rp, ip);
printf("Root2 = %f - %f i", rp, ip);
}
getch();
}
Output of the above program :
Run 1: ----------------- Enter coefficients a, b and c: 1 ↲ -4 ↲ 4 ↲ Roots are real and equal. Root1 = 2.000000 Root2 = 2.000000 Run 2: ----------------- Enter coefficients a, b and c: 1 ↲ -5 ↲ 6 ↲ Roots are real and unequal. Root1 = 3.000000 Root2 = 2.000000 Run 3: ----------------- Enter coefficients a, b and c: 1 ↲ 2 ↲ 3 ↲ Roots are imaginary. Root1 = -1 + 1.414214 i Root2 = -1 – 1.414214 i Note: ↲ indicates enter is pressed.