tags:

views:

177

answers:

2

Hi,

I have a variable ( float slope ) that sometimes will have a value of nan when printed out since a division by 0 sometimes happen.

Trying to do an if else for when that happens, how can I do that? if (slope == nan) doesn't seem to work.

Thanks,
Tee

+2  A: 

Two ways, which are more or less equivalent:

if (slope != slope) {
    // handle nan here
}

Or

#include <math.h>
...
if (isnan(slope)) {
    // handle nan here
}

(man isnan will give you more information, or you can read all about it in the C standard)

Alternatively, you could detect that the denominator is zero before you do the divide (or use atan2 if you're just going to end up using atan on the slope instead of doing some other computation).

Stephen Canon
If I ever came across `if (foo != foo)` in some code I would let out a very audible "WTF". `isnan` seems like a *far* more clear and readable method.
Squeegy
@Squeegy: to someone who is familiar with floating point, they read the same. To someone who isn't, yes, `isnan` is much more clear.
Stephen Canon
A: 

Nothing is equal to NaN — including NaN itself. So check x != x.

Chuck