了解从整数到浮点数的转换

2024-01-13

有人能解释一下 32 位机器上这个奇怪的输出吗?

#include <stdio.h>

int main() {
  printf("16777217 as float is %.1f\n",(float)16777217);
  printf("16777219 as float is %.1f\n",(float)16777219);

  return 0;
}

Output

16777217 as float is 16777216.0
16777219 as float is 16777220.0

奇怪的是 16777217 转换为较低的值,而 16777219 转换为较高的值......


在 IEEE-754 基本 32 位二进制浮点格式中,可以表示从 −16,777,216 到 +16,777,216 的所有整数。从 16,777,216 到 33,554,432,只能表示偶数。然后,从 33,554,432 到 67,108,864,只能表示四的倍数。 (由于这个问题不需要讨论哪些数字可以表示,因此我将省略解释并认为这是理所当然的。)

最常见的默认舍入模式是将精确的数学结果舍入到最接近的可表示值,并且在平局的情况下,舍入到其有效数的低位为零的可表示值。

16,777,217 is equidistant between the two representable values 16,777,216 and 16,777,218. These values are represented as 1000000000000000000000002•21 and 1000000000000000000000012•21. The former has 0 in the low bit of its significand, so it is chosen as the result.

16,777,219 is equidistant between the two representable values 16,777,218 and 16,777,220. These values are represented as 1000000000000000000000012•21 and 1000000000000000000000102•21. The latter has 0 in the low bit of its significand, so it is chosen as the result.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

了解从整数到浮点数的转换 的相关文章

随机推荐