我使用的是 ANSI C89(不是 C++),我想生成 NaN
、-Infinity
和 +Infinity
。
是否有任何标准方法(例如标准宏)? 或者是否有任何平台和编译器无关的方法来生成这些数字?
float f = 0.0 / 0.0; // Is f ALWAYS in any platform is NaN?
我使用的是 ANSI C89(不是 C++),我想生成 NaN
、-Infinity
和 +Infinity
。
是否有任何标准方法(例如标准宏)? 或者是否有任何平台和编译器无关的方法来生成这些数字?
float f = 0.0 / 0.0; // Is f ALWAYS in any platform is NaN?
据我所知,C99中有此功能,而在之前的标准中则没有。
在C99中,您将拥有NAN
和INFINITY
宏。
来自“数学<math.h>
”(§7.12)部分
如果可用,宏INFINITY扩展为类型为float的常量表达式,表示正无穷大或无符号无穷大...
如果您使用的是ANSI C89,则没有此选项。请参见C-FAQ 14.9。
HUGE_VAL
可用于定义无穷大的值。 - mleljcomeau@intrepid:/tmp$ cat test.c; make test; ./test
#include <stdio.h>
int main() {
printf("%f\n", 1.0 / 0);
printf("%f\n", -1.0 / 0);
printf("%f\n", 0.0 / 0);
return 0;
}
cc test.c -o test
test.c: In function ‘main’:
test.c:3: warning: division by zero
test.c:4: warning: division by zero
test.c:5: warning: division by zero
inf
-inf
-nan
奇怪的是,我用这种天真的方法无法得到正向NaN。
f | (1 << 31)
得到 float 类型的正无穷(或任何其他数字)。 - Nearoo-(0.f/0.f)
可以获取 -NaN
。 - S.S. AnneINFINITY
,则还可以使用宏HUGE_VAL
,该宏也在<math.h>
库中定义。
HUGE_VAL
应该在C89/C90标准(ISO/IEC 9899:1990)中可用。nan
被定义为任何指数全部为1,且尾数不全为0的数字(因为那是正无穷)。难点在于生成这个数字,但可以通过以下代码完成:unsigned int p = 0x7F800000; // 0xFF << 23
unsigned int n = 0xFF800000; // 0xFF8 << 20
unsigned int pnan = 0x7F800001; // or anything above this up to 0x7FFFFFFF
unsigned int nnan = 0xFF800001; // or anything above this up to 0xFFFFFFFF
float positiveInfinity = *(float *)&p;
float negativeInfinity = *(float *)&n;
float positiveNaN = *(float *)&pnan;
float negativeNaN = *(float *)&nnan;
memcpy
或传统的除零方法。 - S.S. Anne