C语言 测试 Float 值是否为 NaN

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4744437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:33:13  来源:igfitidea点击:

Testing if Float value is NaN

cfloating-pointsolarisnan

提问by kp11

Possible Duplicate:
Checking if a double (or float) is nanin C++

可能的重复:
检查双精度(或浮点数)是否nan在 C++ 中

I have a requirement to check if float is NaN. By going through some of the links I found the most common check.

我需要检查 float 是否为NaN. 通过浏览一些链接,我发现了最常见的检查。

FLOAT32 f32_test_NaN = (some_value);
if (f32_test_NaN == f32_test_NaN)
{
    //do something;
}
else
{
    // do something;
}

But this does not seem to work for me. My code is as follows:

但这似乎对我不起作用。我的代码如下:

FLOAT32 test_NaN = 0x414570A3;//some value - is this ok?

Debugging on GDB:

在 GDB 上调试:

(gdb) p test_NaN
 = 1.09506982e+09

(gdb) p/x test_NaN
 = 0x41457080 // Hex is not same as init value - What is compiler doing?

So in my case test_NaNis equal to test_NaN.

所以在我的情况下test_NaN等于test_NaN.

Please let me know if any compiler setting has to be done. I am running on solaris. Or is there any other way to check the same.

请让我知道是否必须进行任何编译器设置。我在solaris上运行。或者有没有其他方法可以检查相同。

Thanks in advance.

提前致谢。

采纳答案by Benoit Thiery

The problem is maybe in your initialization (at least that explains the value you see in gdb) :

问题可能出在您的初始化中(至少可以解释您在 gdb 中看到的值):

FLOAT32 test_NaN = 0x414570A3;

The hex value given is considered as an integer and converted to float (with exponent and value) meaning it is stored in a different format.

给定的十六进制值被视为整数并转换为浮点数(带有指数和值),这意味着它以不同的格式存储。

If you want to force the bits inside the float, then you need to memcpy:

如果你想强制浮点数内的位,那么你需要 memcpy:

FLOAT32 test_NaN;
memcpy(&test_NaN, 0x414570A3, 4);

回答by SiegeX

Include math.hand use int isnan(x). Don't forget to link with -lm

包括math.h并使用int isnan(x). 不要忘记链接-lm

回答by Oliver Charlesworth

If <math.h>is not available, then do this:

如果<math.h>不可用,请执行以下操作:

if (x != x)
{
    // x is NaN
}

回答by Oliver Charlesworth

if (x != x)

如果 (x != x)

For x = 0x7FBFFFFF (sign bit 0, a = 0, rest of bits 1)

对于 x = 0x7FBFFFFF(符号位 0,a = 0,其余位 1)

http://en.wikipedia.org/wiki/NaN

http://en.wikipedia.org/wiki/NaN

A bit-wise example of a IEEE floating-point standard single precision (32-bit) NaN: s111 1111 1axx xxxx xxxx xxxx xxxx xxxx where s is the sign, x is the payload, and a determines the type of NaN. If a = 1, it is a quiet NaN; if a is zero and the payload is nonzero, then it is a signaling NaN

IEEE 浮点标准单精度(32 位)NaN 的按位示例: s111 1111 1axx xxxx xxxx xxxx xxxx xxxx 其中 s 是符号,x 是有效载荷,a 确定 NaN 的类型。如果 a = 1,则是安静的 NaN;如果 a 为零且有效载荷非零,则它是一个信令 NaN