I have a variable ( float slope
) that sometimes will have a value of nan when printed out since a division by 0 sometimes happens.
我有一个变量(float斜率),有时会有nan的值,因为有时会出现0。
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.
我试着做一个if-else,当这种情况发生的时候。我该怎么做呢?如果(斜率= nan)不起作用。
4 个解决方案
#1
193
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)
(man isnan会给你更多的信息,或者你可以在C标准中读到相关信息)
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(或者如果你只是在斜率上使用atan而不是做其他的计算的话,可以使用atan2)。
#2
32
Nothing is equal to NaN
— including NaN
itself. So check x != x
.
没有什么能比得上NaN——包括NaN本身。检查x != x。
#3
4
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.
希望这对你有用。
#4
1
In Swift, you need to do slope.isNaN
to check whether it is a NaN.
在Swift中,你需要做斜率。isNaN检查它是否是NaN。
#1
193
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)
(man isnan会给你更多的信息,或者你可以在C标准中读到相关信息)
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(或者如果你只是在斜率上使用atan而不是做其他的计算的话,可以使用atan2)。
#2
32
Nothing is equal to NaN
— including NaN
itself. So check x != x
.
没有什么能比得上NaN——包括NaN本身。检查x != x。
#3
4
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.
希望这对你有用。
#4
1
In Swift, you need to do slope.isNaN
to check whether it is a NaN.
在Swift中,你需要做斜率。isNaN检查它是否是NaN。