John
John

Reputation: 288

Moving element in array

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

}

Upvotes: 2

Views: 183

Answers (3)

codious
codious

Reputation: 3511

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

Upvotes: 0

NPE
NPE

Reputation: 500207

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?

Upvotes: 6

jkerian
jkerian

Reputation: 17016

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)

Upvotes: 2

Related Questions