c++ - 从 double 转换到 size_t 会产生错误的结果?

标签 c++ type-conversion c++20

以下代码有效。
我的问题是,应该 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 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/

    相关文章:

    c# - 使用 C++ 和 C# 的 Visual Studio 2017 单元测试以及未发现的 C++ 测试

    c++ - 我应该使用智能指针吗?

    ios - 将值从字典转换为NSNumber

    c++ - 访问作为非类型模板参数传递的std数组元素会在msvc上给出非编译时常量值

    c++ - 下标运算符中的逗号运算符?

    c++ - 使用概念的模板类方法特化

    通过 Eclipse 的 c++ 和 mysql 连接器

    c++ - Qt 5.5 使用 C++,从 ComboBox 中删除和删除项目也删除了项目之前的所有项目

    c - 初学者类型转换

    三元运算符和类型转换的混淆