I keep getting the result of nan for the x1 and x2 values, can someone please tell me what i'm doing wrong?

#include <iostream>
#include <cmath>

using namespace std;

int main()
{

/*
----------------------------------------------------
This program is by Brandon Cavendish. 9/7/2017
It will find the real roots for a quadratic equation

x1, x2 = -b+-sqrt(b^2-4ac)/2a
----------------------------------------------------
*/
// declaring variables.
double a = 0.0;
double b = 0.0;
double c = 0.0;
double x1 = 0.0;
double x2 = 0.0;
double discriminant = b * b - 4 * a * c;

x1 = -b + sqrt(discriminant) / (2 * a);
x2 = -b - sqrt(discriminant) / (2 * a);

cout << "Enter A:" << endl;
cin >> a;
cout << "Enter B:" << endl;
cin >> b;
cout << "Enter C:" << endl;
cin >> c;

cout << x1 << endl << x2;

return 0;
}
Last edited on
I believe i have fixed it but i still don't believe I'm getting a correct answer.
You are calculating the result before putting in the input.

You also haven't bracketed the whole of the numerator. It's only the sqrt() bit that's getting divided by 2a.
Last edited on
#include <iostream>
#include <cmath>

using namespace std;

int main()
{

/*
----------------------------------------------------
This program is by Brandon Cavendish. 9/7/2017
It will find the real roots for a quadratic equation

x1, x2 = -b+-sqrt(b^2-4ac)/2a
----------------------------------------------------
*/
// declaring variables.
double a = 0.0;
double b = 0.0;
double c = 0.0;
double x1 = 0.0;
double x2 = 0.0;

cout << "Enter A:" << endl;
cin >> a;
cout << "Enter B:" << endl;
cin >> b;
cout << "Enter C:" << endl;
cin >> c;

double discriminant = b * b - 4 * a * c;

x1 = -b + (sqrt(discriminant)) / (2 * a);
x2 = -b - (sqrt(discriminant)) / (2 * a);

cout << "x1 = " << x1 << endl << "x2 = " << x2 << endl;

return 0;
}

this is the code now, i am still receiving a nan result however.
 ``1234567891011121314151617181920212223242526272829303132333435`` ``````#include #include using namespace std; int main() { double a = 0;0; double b = 0.0; double c = 0.0; double x1 = 0.0; double x2 = 0.0; cout << "Enter A:" << endl; cin >> a; cout << "Enter B:" << endl; cin >> b; cout << "Enter C:" << endl; cin >> c; double discriminant = b * b - 4 * a * c; if ( discriminant < 0 ) // Probably a good idea to check ... { cout << "Whoops! Complex roots"; } else { x1 = ( -b + sqrt(discriminant) ) / ( 2 * a ); // bracket CAREFULLY x2 = ( -b - sqrt(discriminant) ) / ( 2 * a ); // bracket CAREFULLY cout << "x1 = " << x1 << endl << "x2 = " << x2 << endl; } }``````
Thank you! It's working now!
closed account (48T7M4Gy)
http://www.cplusplus.com/forum/general/222488/ DUPLICATE
Last edited on
Topic archived. No new replies allowed.