Program returning NaN for quadric equation

My program is returning NaN even though the value in square root function is not negative -1*b + ((sqrt(pow(b,2) * -4 *(a*c))) / 2).
1
2
3
    x = 10;
    y = -1;
    z = 1;


Heres the program:

main.cpp:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include "Quad.h"
double x,y,z; // variable x = 'a', variable y = 'b' and variable z = 'c'.
int main()
{
    x = 10;
    y = -1;
    z = 1;
    std::cout << (Quad(x,y,z)) << std::endl;
    return 0;
}


And Quad.h:

1
2
3
4
5
6
#include <math.h>
double Quad(double a, double b, double c)
{
    double plus = -1*b + ((sqrt(pow(b,2) * -4 *(a*c))) / 2), minus = -1*b - ((sqrt(pow(b,2) * -4 *(a*c))) / 2);
    return(plus, minus);
}


I would like it return the answer and not "NaN". Although I am unsure what is causing this so I am therefore unable to fix the problem. Any help would be appreciated.
return(plus, minus);

This isn't doing what you think it's doing. You've defined your function to return a double. What this is doing is returning the result of the expression (plus, minus), so it's returning the value of minus.
Oh, yeah I noticed that but even if I just do return(plus); it still says: "NaN". I don't get why. The code looks good to me.
pow(-1, 2) = 1 > 0
1 * -4 = -4 < 0
10 * 1 = 10 > 0
-4 * 10. = -40 < 0
sqrt( -40 ) ...... Complex
Is there a way to handle complex numbers in C++?
Ok, I have changed it to this by following the example. However now it just returns: (0,0). I know this is not correct.
Quad.h:

1
2
3
4
5
6
7
#include <math.h>
#include <complex.h>
std::complex <double> Quad(double a, double b, double c)
{
    std::complex <double> answer (-1*b + ((sqrt(pow(b,2) * -4 *(a*c))) / 2, -1*b - ((sqrt(pow(b,2) * -4 *(a*c))) / 2)));
    return(imag(answer));
}
1. You need a complex number argument to use a complex number square root function.
2. There are two solutions to a quadratic equation, which one do you want to return?

Here's an example how to return both:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <complex>

std::pair< std::complex<double>, std::complex<double> > Quad(double a, double b, double c)
{
    std::complex<double> d = b*b - 4*a*c;
    return { (-b+std::sqrt(d))/(2*a), (-b-std::sqrt(d))/(2*a) };
}

int main()
{
    double x = 10;
    double y = -1;
    double z = 1;
    std::cout << "The solutions are: " << Quad(x,y,z).first << " and " << Quad(x,y,z).second << '\n';
}

online demo: http://ideone.com/q3yaO4
Thanks, that fixed the problem.
I just saw this discussion. Cubbi's solution fixed the problem partly because it uses the correct equation. Your original equation contained

sqrt(b2 * (-4ac)

but it should have contained

sqrt(b2 - 4ac)

Also, the total should have been divided by 2a, not 2.

Cubbi's solution corrected both of those.
Thanks.
Topic archived. No new replies allowed.