gpt4 book ai didi

c++ - NaN 到 Bool 转换 : True or False?

转载 作者:IT老高 更新时间:2023-10-28 22:13:47 28 4
gpt4 key购买 nike

C++ 规范或 IEEE 浮点规范的哪一部分规定 NaN 值应转换为 true 而不是 false?

如果我查看 C++ 标准部分 4.12 bool 转换,它会说:

A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true.

现在 IEEE float 表示 NaN 将 false 与任何其他值进行比较。因此,NaN 是真还是假取决于您如何进行比较(如下)。因此,我认为必须明确提及。

value == 0 ? false : true
value != 0 ? true : false

现在,如何转换为整数。下面的简短程序显示,将变量 N​​AN 转换为整数会产生最小整数,而常量会转换为 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 转换为 0 但将 bool 转换为 True 似乎很麻烦。我也不认为 MatLab 之类的东西会使用 int16 之类的函数将 NaN 转换为 0。

那么,说明 NaN 如何转换为 bool 值和整数值的相关标准的具体细节是什么?

我也在标记 C,因为虽然它可能没有定义 bool 转换,但它可能定义了一个整数转换并在条件中使用,我怀疑 C++ 将遵循相同的规则

最佳答案

在 C 和 C++ 中,将 NAN 转换为整数类型(bool 除外)时的行为未定义:

C99 6.3.1.4/1: When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.

C++11 4.9/1: A prvalue of a floating point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type. [ Note: If the destination type is bool, see 4.12. —end note ]

在这两种语言中,将 NAN 转换为 bool(或 _Bool)会得到 true(或 1):

C99 6.3.1.2/1: When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.

C++11 4.12/1: A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true.

NAN 不是零值,不等于零。

关于c++ - NaN 到 Bool 转换 : True or False?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9158567/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com