static_assert(sizeof(unsigned) == 4, ":(");
static_assert(sizeof(double) == 8 ,":(");
unsigned u{42};
double x{u};
g++ 4.7.1 提示此代码:
warning: narrowing conversion of 'u' from 'unsigned int' to 'double' inside { }
为什么这是一个缩小转换?不是每个 unsigned
都可以完美地表示为 double
吗?
最佳答案
Why is this a narrowing conversion?
因为定义包括(我强调):
C++11 8.5.4/7 A narrowing conversion is an implicit conversion [...] from an integer type [...] to a floating-point type, except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type.
u
不是常量表达式,因此无论源类型的所有可能值是否都可以在目标类型中表示,它都是一种缩小转换。
Isn't every
unsigned
perfectly representable as adouble
?
这是定义的实现。在常见的32位unsigned
和double
带52位尾数的情况下,就是这样;但有些实现有较大的 unsigned
和/或较小的 double
表示,因此依赖于该假设的代码是不可移植的。
关于c++ - 缩小从无符号到 double 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11521016/