PROGRAM TO FIND ROOTS OF QUADRATIC EQUATION IN C
In this example, you will learn a program to find the roots of quadratic equations.
The standard form of Quadratic equation is:
ax²+bx+c = 0,
and a,b,c are the real numbers
such that a !=0
b²-4ac is known as the discriminant of the quadratic equation and it tells about the nature of roots of quadratic equation.
1. If discriminant is >0, then roots are real and different.
2. If discriminant is =0, then roots are real and equal.
3.If discriminant is <0, then roots are not real(i.e. complex) and different.
Program:
//Program to find roots of quadratic equation
#include<math.h>
#include<stdio.h>
int main( )
{
double a, b, c, disc, r1, r2 , real_part, imag_part;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
disc = b * b - 4 * a * c;
if (disc > 0)
{
r1 = (-b + sqrt(disc)) / (2 * a);
r2 = (-b - sqrt(disc)) / (2 * a);
printf("r1 = %.2lf and r2 = %.2lf", r1, r2);
}
else if (disc == 0)
{
r1 = r2 = -b / (2 * a);
printf("r1 = r2 = %.2lf;", r1);
}
else
{
real_part = -b / (2 * a);
imag_part = sqrt(-disc) / (2 * a);
printf("r1 = %.2lf+%.2lfi and r2 = %.2f-%.2fi", real_part, imag_part, real_part, imag_part);
}
return 0;
}
#include<math.h>
#include<stdio.h>
int main( )
{
double a, b, c, disc, r1, r2 , real_part, imag_part;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
disc = b * b - 4 * a * c;
if (disc > 0)
{
r1 = (-b + sqrt(disc)) / (2 * a);
r2 = (-b - sqrt(disc)) / (2 * a);
printf("r1 = %.2lf and r2 = %.2lf", r1, r2);
}
else if (disc == 0)
{
r1 = r2 = -b / (2 * a);
printf("r1 = r2 = %.2lf;", r1);
}
else
{
real_part = -b / (2 * a);
imag_part = sqrt(-disc) / (2 * a);
printf("r1 = %.2lf+%.2lfi and r2 = %.2f-%.2fi", real_part, imag_part, real_part, imag_part);
}
return 0;
}
Output:
Enter coefficients a, b and c: 2 12 3
r1= -0.26 and r2= -5.74
r1= -0.26 and r2= -5.74
So that's it ! Just try this code by your own. If you have any doubts then feel free to drop a comment . I'll be happy to answer your questions .
Keep coding....
Comments
Post a Comment