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.
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.
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';
}