Objective-C - float checking for nan

后端 未结 4 1028
春和景丽
春和景丽 2020-12-24 00:15

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 i

相关标签:
4条回答
  • 2020-12-24 00:35

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

    0 讨论(0)
  • 2020-12-24 00:43
     if(isnan(slope)) {
    
         yourtextfield.text = @"";
         //so textfield value will be empty string if floatvalue is nan
    }
    else
    {
         yourtextfield.text = [NSString stringWithFormat:@"%.1f",slope];
    }
    

    Hope this will work for you.

    0 讨论(0)
  • 2020-12-24 00:51

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

    0 讨论(0)
  • 2020-12-24 00:53

    In Swift, you need to do slope.isNaN to check whether it is a NaN.

    0 讨论(0)
提交回复
热议问题