Sanyrual - 1 year ago 97

C++ Question

`#include <iostream>`

#include <conio.h>

#include <math.h>

using namespace std;

int main ()

{

float xstart = -2, xfinal = 2, h = 0.5;

float t, y;

cout << "X start = -2" << endl;

cout << "X final = 2" << endl;

cout << "step = 0.5" << endl << endl;

for ( float x = xstart; x <= xfinal; x+= h)

{

t= sqrt(pow(sin(x),2)) / sqrt(x - 4);

y= sqrt(2 * t + x);

cout << x << " | " << t << " | " << y << endl;

}

cout << endl;

}

This outputs t and y variables as nan. I am out of ideas on how to fix it. The code is just example of the problem, no need to do anything else than the fix nans.

Please help !

Answer Source

```
t= sqrt(pow(sin(x),2)) / sqrt(x - 4);
```

In C++, the square root of a negative number is defined as NAN, "Not a Number". Since the variable `x`

iterates in the range `[-2, 2]`

, you're never going to have this not be NAN, which means all calculations using it will arrive at NAN.

If you're expecting sqrt to return complex numbers, you'll need to make use of `std::complex`

and its various math functions.