NaN 到 Bool 的转换:True 还是 False?
C++ 规范或 IEEE float 规范的哪一部分规定 NaN 值应转换为 true
而不是 false?
如果我查看 C++ 标准部分 4.12 布尔转换,它会显示:
零值、空指针值或空成员指针值是 转换为假;任何其他值都会转换为 true。
现在 IEEE 浮点数表示 NaN 与任何其他值进行比较时为 false。因此 NaN 是真是假取决于您如何进行比较(如下)。因此我认为必须明确提及。
value == 0 ? false : true
value != 0 ? true : false
现在,转换为整数怎么样?下面的简短程序显示,变量 NAN 转换为整数会产生最小整数,而常量会转换为 0(使用 GCC)。这看起来很奇怪。
#include <iostream>
#include <cmath>
void write( double r, int i, bool b )
{
std::cout << r << " == " << i << " == " << (b ? "True" : "False") << std::endl;
}
int main()
{
double value = NAN;
write( value, value, value );
write( NAN, NAN, NAN );
}
输出:
nan == -2147483648 == True
nan == 0 == True
NaN 到零的转换,但 bool 转换为 True 似乎令人不安。我也不认为像 MatLab 这样的东西会使用像 int16
这样的函数将 NaN 转换为 0。
那么,规定 NaN 如何转换为布尔值和整数值的相关标准有哪些具体细节呢?
我也标记了 C,因为虽然它可能没有定义布尔转换,但它可能定义了整数转换并在条件中使用,我怀疑 C++ 将遵循相同的规则
What part of the C++ spec, or the IEEE float spec, states that a NaN value should convert to true
as opposed to false?
If I look at the C++ standard section 4.12 Boolean Conversions it says:
A zero value, null pointer value, or null member pointer value is
converted to false; any other value is converted to true.
Now IEEE floats say that NaN compares false to any other value. So whether NaN is true or false depends on how you do your comparision (below). Thus I presume there must be an explicit mention.
value == 0 ? false : true
value != 0 ? true : false
Now, what about conversion to an integer. The short program below shows that a variable NAN converted to an integer results in the minimum integer, whereas a constant gets converted to 0 (using GCC). This seems odd.
#include <iostream>
#include <cmath>
void write( double r, int i, bool b )
{
std::cout << r << " == " << i << " == " << (b ? "True" : "False") << std::endl;
}
int main()
{
double value = NAN;
write( value, value, value );
write( NAN, NAN, NAN );
}
Output:
nan == -2147483648 == True
nan == 0 == True
The conversion of a NaN to zero but bool conversion as True seems troubling. I also not that something like MatLab will convert a NaN to 0 using a function like int16
.
So, what are the specifics of the relevant standards that state how NaN converts to boolean and integer values?
I'm tagging C as well, since while it may not define the boolean conversion, it probably defines an integral conversion and use in a conditional and I suspect C++ will follow the same rules
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 C 和 C++ 中,将
NAN
转换为整数类型(bool
除外)时的行为是未定义的:在两种语言中,将
NAN
转换为bool
(或_Bool
)会得到true< /code>(或
1
):NAN
不是零值,并且比较时不等于零。In both C and C++, the behaviour is undefined when converting
NAN
to an integer type (other thanbool
):In both languages, converting
NAN
tobool
(or_Bool
) givestrue
(or1
):NAN
is not a zero value, and doesn't compare equal to zero.