问题描述
#include <stdio.h>
#include <math.h>
int main()
{
long double x = NAN;
printf("x = %Lg\nisnan(x) = %d\n",x,isnan(x));
return 0;
}
运行上面的程序时,我得到输出:
x = nan
isnan(x) = 0
根据联机帮助页,当参数为NaN时,isnan
应该返回非零值。那么为什么它返回零呢?
解决方法
不确定是否相关,但是...
$ gcc so64374723.c -lm && ./a.out x = nan isnan(x) = 1 $ gcc -ffast-math so64374723.c -lm && ./a.out x = nan isnan(x) = 0 $ gcc -fsignaling-nans so64374723.c -lm && ./a.out x = nan isnan(x) = -1 $ clang -ffast-math so64374723.c -lm && ./a.out x = nan isnan(x) = -1 $ clang so64374723.c -lm && ./a.out x = nan isnan(x) = -1,
根据相同的联机帮助页,使用-lm
时应该“与isnan
链接”。在将-lm
添加到gcc
命令行并重新编译之后,isnan(x)
返回了1。
不确定之前为什么没有给出链接器错误。我想它要么不会在libm
之外实现,要么会正确实现。虽然我可能会丢失一些东西。
编辑:设置-fsignaling-nans
也可以(感谢链接@P__J__。)有趣的是,在这种情况下,它返回-1而不是1,但这仍然是正确的行为,因为它是非零值。