teepusink teepusink - 1 year ago 135
Objective-C Question

Objective C - float checking for nan

I have a variable (

float slope
) that sometimes will have a value of nan when printed out since a division by 0 sometimes happens.

I am trying to do an if-else for when that happens. How can I do that?
if (slope == nan)
doesn't seem to work.

Answer Source

Two ways, which are more or less equivalent:

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


#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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download