C++ 如何将 int 舍入为 float/double?

How does C++ round int to float/double?

如果 signed/unsigned 整数隐式转换为 floats/doubles,C++ 如何舍入?

喜欢:

int myInt = SomeNumberWeCantExpressWithAFloat;
float myFloat = myInt;

我的大学脚本如下所述:结果值是最接近原始值的可表示值,其中以实现定义的方式打破了联系。

请解释 "nearest representable value" 的计算方式以及 "where ties are broken in an implementation-defined fashion" 的含义。

编辑:
由于我大部分时间都在使用 GCC,请提供有关 GCC 默认使用的浮点表示的附加信息(如果有的话)。

单精度浮点数有24位尾数。在 32 位 int 表示值高于 224 和低于 -(224) 的系统上需要舍入。

Value 224+1 = 16777217 是第一个无法用 IEEE binary32 格式准确表示的 int。有两个 float 表示可用 - 16777216,它比精确值低 1,而 16777218,它比精确值高,也高 1。因此,我们有一个平局,这意味着 C++ 可以选择这两种表示之一。

IEEE 754 指定了关于如何舍入整数的 5 种不同的舍入模式:

一种非常常见的模式称为:舍入到最近,与偶数相关


来自 GCC Wiki:

Without any explicit options, GCC assumes round to nearest or even and does not care about signalling NaNs. Compare with C99's #pragma STDC FENV ACCESS OFF. Also, see note on x86 and m68080.


四舍五入到偶数

来自维基百科:

Rounding a number y to the nearest integer requires some tie-breaking rule for those cases when y is exactly half-way between two integers — that is, when the fraction part of y is exactly 0.5.

在这种情况下,会选择偶数。这适用于正数和负数。


来源:


随时编辑。欢迎提供有关 rational/irrational 数字转换规则的更多信息。