-1

My problem is somewhere in the definition of first_x and second_x. When I call the quad_eq function, I get a -nan(ind) return based on the code below. If I change the .pushback() method parameter to be a literal integer, I get that integer returned instead of NaN. This leads me to believe that the problem is with my calculation/definition of first_x and second_x. Maybe there is some trick to C++ that I am not seeing or understanding. Can anyone see what my problem is? (If this helps I am working out of Bjarne Stroustrup's C++ Principles and Practice Using C++ where he gives me the std_lib_facilities.h file to use as I do not understand headers yet)

vector<double>quad_eq(double a, double b, double c) {
    vector<double>answers;
    double first_x = (-b + sqrt((b * 2) - (4 * a * c))) / 2 * a;
    double second_x = (-b - sqrt((b * 2) - (4 * a * c))) / 2 * a;
    answers.push_back(first_x);
    answers.push_back(second_x);
    return answers;
}

1 Answers1

3

Depending on the input, you are taking the square root of negative numbers, so you get NaN (which is, in fact, a double) out of that, and any other operations propagate that.

Sidenote: the code you show doesn't compile as-is, because it is missing #include <vector> and using namespace std;. The latter is also usually frowned upon.

stijn
  • 34,664
  • 13
  • 111
  • 163
  • My code is compiling. I have a header included made by the author of this book that deals with that even though I do not understand it yet. My problem is something with my calculation. I'm thinking it is maybe my parenthesis at this point. I am putting in perfectly legitimate quadratic formula inputs and they are still coming out as NaN even though on paper they come out how they should. – ObamaBinTrappin Jul 09 '17 at 06:50
  • 1
    @ObamaBinTrappin `b * b` is not the same as `b * 2`. – melpomene Jul 09 '17 at 06:51
  • Yes, thank you. I fixed that but it has not solved the NaN problem. – ObamaBinTrappin Jul 09 '17 at 06:54
  • 1
    If you call `quad_eq( 1, 2, 3 )` then `b * 2 - (4 * a * c )` equals -8, and `sqrt(-8)` in c++ returns a double, not a complex number, and so it chooses to return NaN here because it cannot possibly express the result in a double. What do you expect to happen instead? You don't specify that.. Do you need a complex number? (see https://stackoverflow.com/questions/7042760/negative-square-root for instance) – stijn Jul 09 '17 at 06:56