經常在AS3里面收獲到NaN,但一直認為C++是弱類型的,只管內存,再加上平時都跟uint32打交道比較多,
才會在今天踩到陷阱。碰到一個值為-nan(0x400000)造成的crash.
google了一下收獲到:
http://stackoverflow.com/questions/570669/checking-if-a-double-or-float-is-nan-in-c
for a float f, f != f will be true only if f is NaN.
對於float類型變量f,f != f 僅在f 是 NaN時成立。
看來判斷float是否為有效值是還得多一個判斷f==f
直接看代碼:
#include <stdio.h>
int main(){
unsigned int i = 0x400000;
float f = 0.0f;
printf("{f:%f,i:%u}\n",f,i);
*((unsigned int *)&f)=i;
printf("{f:%f,i:%u}\n",f,i);
f = 0.0f/0.0f;
if(f != f)
printf("f != f,%f,%u\n",f,*((unsigned int *)&f));
if(f > 0.0f || f == 0.0f || f < 0.0f)
printf(" f > 0.0f || f == 0.0f || f < 0.0f)\n");
else
printf("cool!\n");
return 0;
}
補充一下c++的nan怎么出
#include <limits> #include <assert.h> void foo( double a, double b ) { assert( a != b ); } int main() { typedef std::numeric_limits<double> Info; double const nan1 = Info::quiet_NaN(); double const nan2 = Info::quiet_NaN(); foo( nan1, nan2 ); }
原來,魚非魚啊