为什么 int 被缩小到浮动?

vla*_*don 2 c++ language-lawyer type-narrowing

举个例子:

#include <iostream>

void foo(float) {}

int main()
{
    int i{43};
    foo(float{i});

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译器(铛,MSVC)不编译这个(GCC编译,但有警告)non-constant-expression cannot be narrowed from 'int' to 'float' in initializer list

为什么编译器说int缩小floatfloat更广泛的int

Ian*_*Ian 5

也就是说,因为精度浮子,这是只有7位数的,尽管它有更大的范围比INT。

因此,如果您尝试以超过 7 位的精度表示 int 数字以进行浮点运算,则可能会有所损失。- 从这个意义上说,它被称为缩小。虽然浮子具有更宽范围比INT,它具有更小的精度。

此外,浮点表示是近似值——也就是说,它不表示精确的数字(2 的幂除外)。从这个意义上说,int 也变窄了。