- #1

- 102

- 0

## Main Question or Discussion Point

**[C++] coding a quadratic root finder with "if statements"**

//This program solves the qudratic equation

#include <iostream>

#include<cmath>

#include<iomanip>

using namespace std;

int main()

{

//Declaring Varibles

double coefA;

double coefB;

double coefC;

double x1;

double x2;

double x3;

//Initialize varibles

x1=0.0;

x2=0.0;

x3=0.0;

coefA=0.0;

coefB=0.0;

coefC=0.0;

//Input of values

cout<<"Enter the value of the coefficent of the second order (x squared) term:";

cin>>coefB;

cout<<"Enter the value of the coefficent of the first order term:";

cin>>coefA;

cout<<"Enter the value of the constant term:";

cin>>coefC;

cout<<"\n\n";

cout<<"The coefficents of the quadratic equation are:\n";

cout<<" Coefficent of the second order term is "<<coefB<<",\n";

cout<<" Coefficent of the first order term is "<<coefA<<",\n";

cout<<" Coefficent of the constant term is "<<coefC<<"\n";

cout<<"\n\n\n";

//Equation body

x1=(-coefB+sqrt(coefB*coefB-4*coefA*coefC))/(2*coefA);

x2=(-coefB-sqrt(coefB*coefB-4*coefA*coefC))/(2*coefA);

x3=-coefC/coefB;

//"If" staements that returns the appropriate number of roots

if(coefA==0&&coefB==0)

{

if(coefC==0&&coefB==0)

{

cout<<"There are infinite number of possible solutions";

}

else

{

cout<<"There are no real roots.";

}

}

else if (fabs(coefA-0)<0.005)

{

cout<<"There is one real root = "<<fixed<<setprecision(2)<<x3;

}

else if((coefB*coefB-4*coefA*coefC)>0.0)

{

cout<<"There are two real roots, root 1 = "<<fixed<<setprecision(2)<<x1<<" root2 = "<<x2;

}

else if(fabs(x1-x2)<0.005)

{

cout<<"There is one double real root, root1 = "<<fixed<<setprecision(2)<<x1;

}

else

{

cout<<"There are no real roots.";

}

return 0;

}

Above is my code so far, i'm not sure why when i enter any value at all, the out put will always be the same giving me "There are no real roots".

I'm assuming there is something wrong with the first "if" statements since before i put that in, it gave me the correct roots. can someone give me some guidance?

Last edited: