2

I'm not sure why the code below is not working, I'm trying to find the value of NaN in the array and then move NaN to the first element in the array (element 0) and swap the existing element 0 with wherever the NaN was. Please can you check my code out? Maybe you guys/girls can see something I can't?

Thanks in advance!

#define NaN (float)(1e308*10*0)


void movenan(float array[], int size)
{
int w;
float hold;
float move;

for(w = 0; w < SIZE - 1; w++)
{
    if(array[w] == NaN)
    {
        hold = array[w];
        array[w] = array[0];
        array[0] = hold;
    }
}

}

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
John
  • 278
  • 1
  • 3
  • 8
  • I think you can't test for NaN this way. See this post: http://stackoverflow.com/questions/570669/checking-if-a-double-or-float-is-nan-in-c – dbrank0 Feb 24 '12 at 08:41
  • Also the loop be for(w = 0; w < SIZE; w++) – Avi Feb 24 '12 at 08:43
  • I assume you want to loop over the array until `w < size` rather than `w < SIZE - 1`, not? `<` means "smaller than" so the -1 isn't needed (unless you want to skip the last element in the array). –  Feb 24 '12 at 08:49

3 Answers3

6

Your NaN check is wrong: NaNs don't compare equal to anything, including themselves.

Use isnan() to check whether the value is NaN.

If isnan() is not available, the canonical way to check whether f is NaN is as follows: f != f. This evaluates to true iff f is NaN.

There is a lot more information here: Checking if a double (or float) is NaN in C++ (the question is about C++, but there is a lot of information about C as well.)

Finally, the terminal condition of your for loop looks suspect. Did you mean < SIZE or <= SIZE-1?

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

I suspect the problem is your nan comparison. NaNs are not that consistant.

You should be using the isnan() function, or one of it's variants. If you don't want to use isnan for some silly reason, the easiest way to check for a nan is if(array[w] != array[w]). With a real NAN, that should work, presuming your optimizer doesn't take that out.

You're also off by one on that loop (should be w < size, SIZE is probably something else, and you don't want to go until size-1)

jkerian
  • 16,497
  • 3
  • 46
  • 59
  • 1
    If the optimizer eliminates `!=` on floats, you really need a better compiler. –  Feb 24 '12 at 08:51
0

If you trying to parse the whole array then the condition should be w<size otherwise it parses only till the second last element.

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
codious
  • 3,377
  • 6
  • 25
  • 46
  • I cant see my whole text here for some reason. Your loop condition should be w – codious Feb 24 '12 at 08:45
  • 1
    The `<` character starts some HTML formatting. You need to use code markup (see the edit). Click the `?` button on the right-hand side of the button bar in the editor for more information about markup. – Gilles 'SO- stop being evil' Feb 24 '12 at 10:09