C++ Program to evaluate the roots of a Quadratic Equation(real and imaginary)

//To find the roots of a quadratic equation
using namespace std;
int main()
double a,b,c,d,e,f,g,root1,root2;    //a,b,c for coefficients, d,e,f,g are used in making                         calculations easier and root1,root2 are the solutions
cout<<"Enter the coefficient of x^2\n";    //Input the coefficient of x^2 cin>>a;
cout<<"Enter the coefficient of x\n";    //Input the coefficient of x cin>>b;
cout<<"Enter the coefficient of x^0\n";    //Input the coefficient of x^0 cin>>c;
d=pow(b,2)-4.0*a*c;             //b^2-4ac
if (d==0)                //condition for real and equal roots
root1=(-b)/(2.0*a);            //root
cout<<"\nThe  equation has equal and real roots, that are, \n"<<root1<<" &"<<root1; } else if (d>0)                //condition for real and distinct roots
e=sqrt(d);                //(b^2-4ac)^1/2
root1=(-b+e)/(2*a);            //[-b+(b^2-4ac)^1/2]/(2*a)
root2=(-b-e)/(2*a);            //[-b-(b^2-4ac)^1/2]/(2*a)
cout<<"\nThe equation has distinct and real roots, that are, \n"<<root1<<" &"<<root2;
else if (d<0)                //condition for imaginary roots
d=-d;                    /*for making the value of (b^2-4ac)^1/2 as positive
                    so that its root can be taken*/
e=sqrt(d);                //(b^2-4ac)^1/2
f=-b/(2.0*a);                //Real Part
g=e/(2.0*a);                //Imaginary part
cout<<"\nThe equation has imaginary roots, that are,\n"<<f<<"+"<<g<<"i &"<<f<<"-"<<g<<"i\n";
return 0;
/*Sample Output
Roots are: 0.260325 & -0.323483
[wpedon id="7041" align="center"]

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.