从double转换到size_t会产生错误的结果?
以下代码有效。我的问题是,应该 2) 不会导致非常接近 1) 的结果吗?为什么 2) 投到这么小的数量?因此,也许值得注意的是 2) 正好是 1) 的一半:
std::cout << "1) " << std::pow(2, 8 * sizeof(size_t)) << std::endl;
std::cout << "2) " << static_cast<size_t>(std::pow(2, 8 * sizeof(size_t))) << std::endl;
输出是:
- 18446744073709551616
- 9223372036854775808
回答
这是由于规范的那部分:
7.3.10 浮点积分转换[conv.fpint]
浮点类型的纯右值可以转换为整数类型的纯右值。转换截断;也就是说,小数部分被丢弃。如果截断的值无法在目标类型中表示,则行为未定义。
该值18446744073709551616(即被截断的部分)大于std::numberic_limit<size_t>::max()您系统上的值,因此,该转换的行为未定义。
- The truncation is unimportant for this case. The number is too large whether a fractional portion was lopped off or not.