-1.#IND ???

When I use the quadratic formula to try and get the roots, it always comes out as -1.#IND. I'm guessing it's because c++ won't allow the sqrt of a negative number. How do i fix this problem? Thanks.

#include <iostream>
#include <math.h>
#include <complex>
using namespace std;
int main()
{
double a,b,c,nat_of_root,root_1,root_2;
char again;
do
{
cout << "Enter the desired value for 'a', then press Enter."<<endl;
cin >> a;
cout << "Enter the desired value for 'b', then press Enter."<<endl;
cin >> b;
cout << "Enter the desired value for 'c', then press Enter."<<endl;
cin >> c;

nat_of_root=(b*b)-((4*a*c));
root_1=((-b)+ sqrt((b*b)*(-4*a*c)))/(2*a);
root_2=((-b)- sqrt((b*b)*(-4*a*c)))/(2*a);

if ((nat_of_root==0))
{cout << "The number is a single real root, which is "<<endl;
cout << root_1<<" and "<<root_2<<endl;
}else
if ((nat_of_root<0))
{cout << "The numbers are negative and have 2 complex roots, which are "<<endl;
cout << root_1<<" and "<<root_2<<endl;
}else
if ((nat_of_root>0))
{cout << "The numbers are positive and have two real roots, which are "<<endl;
cout << root_1<<" and "<<root_2<<endl;
}


cout << " Would you like to try again?(y/n)\n"<<endl;
cin >> again;
} while (again =='y' || again =='Y');

return 0;
}


This:
 
    root_1=((-b)+ sqrt((b*b)*(-4*a*c)))/(2*a);

should be:
 
    root_1 = (-b + sqrt(b*b - 4*a*c) )/(2*a);

Notice the minus sign was in the wrong place, the terms were multiplied instead.

But you already calculated nat_of_root=(b*b)-((4*a*c)); so you can place that in the formula instead:
 
    root_1 = (-b + sqrt(nat_of_root))/(2*a);


The same applies for the other root.

If necessary, you could avoid calculating the sqrt() except when the roots are real (nat_of_root >= 0)

Topic archived. No new replies allowed.