81

我有一个变量,由于有时会发生除法,因此有时会在打印出时float slope具有值。nan 0

当这种情况发生时,我正在尝试做一个 if-else。我怎样才能做到这一点?if (slope == nan)似乎不起作用。

4

4 回答 4

210

两种方式,或多或少是等价的:

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

或者

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

man isnan将为您提供更多信息,或者您可以在 C 标准中阅读所有相关信息)

或者,您可以在进行除法之前检测到分母为零(或者atan2如果您最终要atan在斜率上使用而不是进行其他计算,则使用)。

于 2010-08-12T21:03:09.170 回答
36

没有什么是平等的NaN——包括NaN它自己。所以检查x != x

于 2010-08-12T21:03:16.363 回答
6
 if(isnan(slope)) {

     yourtextfield.text = @"";
     //so textfield value will be empty string if floatvalue is nan
}
else
{
     yourtextfield.text = [NSString stringWithFormat:@"%.1f",slope];
}

希望这对你有用。

于 2012-10-01T11:31:33.177 回答
2

在 Swift 中,您需要slope.isNaN检查它是否为 NaN。

于 2016-02-24T20:22:39.487 回答