Write a c program for finding the roots of the quadratic equation using conditional operator
double Root_1,Root_2;
int SolveQuadratic(double aa, double bb, double cc, double *x1, double *x2)
{
double temp,t;
int n;
temp = (bb*bb) - (4*aa*cc);
cout<<"\n";
if(aa!=0)
{
if(temp<0)
{
t = -temp;
t = sqrt(t);
cout<<"\n Roots are Imaginary.";
cout<<"\nRoot-1 = "<<(-bb/(2*aa))<<" + "<<(t/(2*aa));
cout<<"\nRoot-1 = "<<(-bb/(2*aa))<<" - "<<(t/(2*aa));
n = -1;
*x1=0; *x2=0;
}
if(temp==0)
{
Root_1 = -bb/(2*aa);
Root_2 = Root_1;
cout<<"\nRoots are real and Equal.";
cout<<"\nRoots are "<<Root_1<<" and "<<Root_2;
n=1;
*x1=Root_1; *x2 = Root_2;
}
if(temp>0)
{
Root_1 = (-bb + sqrt(temp))/(2*aa);
Root_2 = (-bb - sqrt(temp))/(2*aa);
cout<<"\nRoots are real and Unequal.";
cout<<"\nRoots are "<<Root_1<<" and "<<Root_2;
n=2;
*x1=Root_1; *x2 = Root_2;
}
}
else
{
n = -2;
*x1 = -cc/bb;
*x2=0;
}
return(n);
}
main(void)
{
double a,b,c,x,y;
int m;
cout<<"\nThe Quadratic Equation : a x^2 + bx + c";
cout<<"\n\nEnter a = "; cin>>a;
cout<<"\nEnter b = "; cin>>b;
cout<<"\nEnter c = "; cin>>c;
cout<<"\nThe Quadratic Equation : ("<<a<<") x^2 + ("<<b<<") x + "<<c;
m = SolveQuadratic(a,b,c,&x,&y);
cout<<"\n\nThe returned Int Value n = "<<m;
cout<<"\n\n";
if(m==0) cout<<"\n\nn = "<<m<<"\tNo Real Root";
if(m==1) cout<<"\n\nn = "<<m<<"\tBoth roots are real and equal.";
if(m==2) cout<<"\n\nn = "<<m<<"\tTwo Real roots.";
if(m==-1) cout<<"\n\nn = "<<m<<"\tComplex Roots.";
if(m==-2) cout<<"\n\nn = "<<m<<"\tLinear Equation.";
return(0);
}
Comments
Leave a comment