为什么`isnan`会将0的长整型数返回0到NAN?

问题描述

#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,但这仍然是正确的行为,因为它是非零值。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...