测试 Float 值是否为 NaN
可能的重复:
检查双精度数(或浮点数)是否为C++ 中的 nan
我需要检查 float 是否为 NaN
。通过浏览一些链接,我找到了最常见的检查。
FLOAT32 f32_test_NaN = (some_value);
if (f32_test_NaN == f32_test_NaN)
{
//do something;
}
else
{
// do something;
}
但这似乎对我不起作用。我的代码如下:
FLOAT32 test_NaN = 0x414570A3;//some value - is this ok?
在GDB上调试:
(gdb) p test_NaN
$1 = 1.09506982e+09
(gdb) p/x test_NaN
$2 = 0x41457080 // Hex is not same as init value - What is compiler doing?
所以在我的例子中,test_NaN
等于test_NaN
。
如果需要进行任何编译器设置,请告诉我。我在Solaris 上运行。或者有没有其他方法可以检查相同的情况。
提前致谢。
Possible Duplicate:
Checking if a double (or float) isnan
in C++
I have a requirement to check if float is NaN
. By going through some of the links I found the most common check.
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) p test_NaN
$1 = 1.09506982e+09
(gdb) p/x test_NaN
$2 = 0x41457080 // Hex is not same as init value - What is compiler doing?
So in my case test_NaN
is equal to 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.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
包含
math.h
并使用int isnan(x)
。不要忘记使用-lm
链接Include
math.h
and useint isnan(x)
. Don't forget to link with-lm
如果
不可用,则执行以下操作:If
<math.h>
is not available, then do this:if (x != x)
对于 x = 0x7FBFFFFF(符号位 0,a = 0,其余位 1)
http://en.wikipedia.org/wiki/NaN
if (x != x)
For x = 0x7FBFFFFF (sign bit 0, a = 0, rest of bits 1)
http://en.wikipedia.org/wiki/NaN
问题可能出在您的初始化中(至少解释了您在 gdb 中看到的值):
给定的十六进制值被视为整数并转换为浮点数(带有指数和值),这意味着它以不同的格式存储。
如果你想强制浮点数内的位,那么你需要 memcpy:
The problem is maybe in your initialization (at least that explains the value you see in gdb) :
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: