c++ - 为什么编译时浮点计算的结果可能与运行时计算的结果不同?

标签 c++ floating-point language-lawyer constexpr floating-accuracy

constexpr: Introduction ,演讲者提到“编译时浮点计算可能与运行时计算的结果不同”: enter image description here

而原因与“交叉编译”有关。

老实说,我不太清楚这个想法。恕我直言,不同的平台也可能有不同的整数实现。

为什么它只影响 float ?或者我错过了什么?

最佳答案

Why does it only affect floating points?

因为标准没有对浮点运算精度施加限制。

根据 expr.const , 强调我的:

[ Note: Since this document imposes no restrictions on the accuracy of floating-point operations, it is unspecified whether the evaluation of a floating-point expression during translation yields the same result as the evaluation of the same expression (or the same operations on the same values) during program execution. [ Example:

bool f() {
    char array[1 + int(1 + 0.2 - 0.1 - 0.1)];  // Must be evaluated during translation
    int size = 1 + int(1 + 0.2 - 0.1 - 0.1);   // May be evaluated at runtime
    return sizeof(array) == size;
}

It is unspecified whether the value of f() will be true or false. — end example ]
— end note ]

关于c++ - 为什么编译时浮点计算的结果可能与运行时计算的结果不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50959021/

相关文章:

c++ - 我可以克隆 C++ 对象的字节,覆盖原始字节,然后将这些字节复制回来吗?

python - 如果 n 位损坏或丢失,如何找到 float 的精度

c++ - 我想看一个函数名称在嵌套名称说明符中被忽略的示例

C++ 将字符串写入文本文件中的一行;换行问题\n 不工作

c++ - 需要使用递归c++计算算术级数的总和

c# - 将 double 转换为 float 是否总是返回相同的值?

c++ - 从 int 到 float 并返回时符号发生变化

c++ - gcc 和 clang 在可变类模板中调用可变成员函数模板时的行为不同

c++ - Boost C++ 正则表达式 - 如何获得多个匹配项

C++ 帮助 - getline