Coding help with if statements and comparisons

//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;
double x4;

//Initialize varibles
x1=0.0;
x2=0.0;
x3=0.0;
x4=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;

x4=coefB*coefB-4*coefA*coefC;

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

if((fabs(coefA-0.0)<0.00001)&&(abs(coefB-0.0)<0.00001))
{
if((fabs(coefA-0.0)<0.00001)&&(abs(coefB-0.0)<0.00001))
{
cout<<"There are infinite number of possible solutions";
}
else
{
cout<<"There are no real roots.";
}
}


else if (fabs(coefA-0)<0.00001)
{
cout<<"There is one real root = "<<fixed<<setprecision(2)<<x3;
}

else if(fabs(x4-0.0)<0.00001)
{
cout<<"There are no real roots.";
}

else if(fabs(x1-x2)<0.00001)
{
cout<<"There is one double real root, root1 = "<<fixed<<setprecision(2)<<x1;
}

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


return 0;
}



The problem o have is when i input values where x4coefB*coefB-4*coefA*coefC would = some negative vale, the program would always skip:
else if(fabs(x4-0.0)<0.00001)
{
cout<<"There are no real roots.";
}
even though x4 is <0.0.
I can't see where i went wrong,any hints?

You use fabs so fabs(x4-0.0)<0.00001 is not necessary true when x4 is negative. If x4 is less than -0.00001 it will return false.
Last edited on
can i just write x4<0.00001 or is that bad due to machine precision.
If you want to check if x4 is less than 0 I don't see why you don't just check it like if (x4 < 0).
Topic archived. No new replies allowed.