Subscribe

RSS Feed (xml)

Wednesday, July 29, 2009

Write a C program to find the roots of a Quadratic equation

#include(stdio.h) //note use '<' & '>' in place of '(' & ')'
#include(conio.h)
#include(math.h)
int main( )
{
int a , b, c, d;
float x1, x2;
ab:
printf("Enter the value of a, b, c:");
scanf("%d%d%d", &a, &b, &c);
if(a==0)
{
printf("\nIt is a Linear Equation");
prinft("\nRe-Enter the data again.");
goto ab;
}
d=(b*b)-(4*a*c);
if(d==0)
{
printf("\nRoots are real and equal");
x1= x2=(-b)/(2*a);
printf("\nRoots are: %f \t %f ", x1, x2);
}
else
{
if(d<0)
printf("\nRoots are imaginary");
else
{
x1=((-b)+sqrt(d))/(2*a);
x2=((-b)-sqrt(d))/(2*a);
printf("\nRoots are real");
printf("\nRoots are : %f \t %f", x1, x2);
}
}
getch( );
}
Output:-
Enter the values of a, b,c : 5
2
4
Roots are imaginary.

6 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. Cann't we find the imaginary roots also?

    ReplyDelete
  3. what about the roots ??
    cant we get them?

    ReplyDelete
  4. yes.. we can find them using the formula
    x1=-b/(2.0*a);
    x2=(sqrt(-d))/(2*a);
    printf("The roots are imaginary");
    printf("\n The roots are\n");
    printf("\n%0.2f+i%0.2f\n",x1,x2);
    printf("\n%0.2f+%0.2f\n",x1,x2);

    ReplyDelete
  5. printf("\n%0.2f+i%0.2f\n",x1,x2); //should be +ve
    printf("\n%0.2f-%0.2f\n",x1,x2); //Should be -ve

    ReplyDelete