以下代码有效。
我的问题是,应该 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;
输出是:最佳答案
这是由于规范的那部分:
7.3.10 Floating-integral conversions [conv.fpint]
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.
18446744073709551616
值(即被截断的部分)在您的系统上大于 std::numberic_limit<size_t>::max()
,因此,该转换的行为未定义。
关于c++ - 从 double 转换到 size_t 会产生错误的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65012526/