我有一个变量 float slope
,由于有时会发生除以 0
的情况,因此打印出来时它的值有时会是 nan
。
我正在尝试在发生这种情况时执行 if-else。我怎样才能做到这一点? if (slope == nan)
似乎不起作用。
最佳答案
两种方式,或多或少是等价的:
if (slope != slope) {
// handle nan here
}
或者
#include <math.h>
...
if (isnan(slope)) {
// handle nan here
}
(man isnan
将为您提供更多信息,或者您可以阅读 C 标准中的所有相关信息)
或者,您可以在进行除法之前检测到分母为零(如果您最终要在斜坡上使用 atan
,则使用 atan2
而不是做一些其他的计算)。
关于Objective-C - 对 nan 进行浮点检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3471988/