Objective-C - 浮动检查nan

tee*_*ink 77 floating-point objective-c

我有一个变量(float slope),有时在打印时会有一个nan值,因为有时会发生除0.

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

Ste*_*non 203

两种方式,或多或少相当:

if (slope != slope) {
    // handle nan here
}
Run Code Online (Sandbox Code Playgroud)

要么

#include <math.h>
...
if (isnan(slope)) {
    // handle nan here
}
Run Code Online (Sandbox Code Playgroud)

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

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

  • 如果我在某些代码中遇到`if(foo!= foo)`,我会发出一个非常可听见的"WTF".`isnan`看起来像一个*远*更清晰和可读的方法. (93认同)
  • @Squeegy:对于熟悉浮点的人,他们读的相同.对于不是的人,是的,`isnan`更清楚. (5认同)
  • `slope!= slope`很棒.谢谢! (3认同)
  • @AndrewHeinlein:不完全是.它扩展为`x!= x`,除非你用-ffast-math或类似编译,在这种情况下它扩展为调用`__isnanf`或`__isnand`(因为`x!= x`不会在-ffast-math下正常工作).因此通常最好使用`isnan`. (2认同)

Chu*_*uck 35

没有什么是相同的NaN- 包括NaN它自己.所以检查x != x.

  • 感谢您的解释! (3认同)

Asw*_*ose 5

 if(isnan(slope)) {

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

希望这对你有用.