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

}

3
  • I think you can't test for NaN this way. See this post: stackoverflow.com/questions/570669/… Commented Feb 24, 2012 at 8:41
  • Also the loop be for(w = 0; w < SIZE; w++) Commented Feb 24, 2012 at 8: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). Commented Feb 24, 2012 at 8:49

3 Answers 3

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?

Sign up to request clarification or add additional context in comments.

Comments

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)

1 Comment

If the optimizer eliminates != on floats, you really need a better compiler.
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.

2 Comments

I cant see my whole text here for some reason. Your loop condition should be w<size
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.