printf 函数背后的底层逻辑是什么?
What is the underlying logic behind printf function?
最近,我在用 C 来测试不同的东西。
printf("%d", 0.4);
将打印 -1717986918。
我理解这一定与浮点数的二进制表示有关。但是,在使用一些在线资源将 0.4 转换为浮点数后,二进制表示与 -171986918 不匹配。请解释这段代码背后到底发生了什么。
PS:我在 Windows 64 位上使用 gcc 编译器 运行 它。
I understand that this must be related to the binary representation
不,这是未定义的行为 (UB)。
"%d"
与 double
不匹配。
If a conversion specification is invalid, the behavior is undefined. C17dr § 7.21.6.1 9
语言未定义 (UB) 输出和行为。什么事都有可能发生。
在某些系统上,UB 可能会看到二进制模式的一部分被解释为 int
。
在另一个系统上,int
和 double
以不同的方式传递,看到的输出基于垃圾。
在另一个系统或另一天,不好的 事情发生了。
都是未定义行为(UB)
explain what really happened
要了解 OP 的机器中可能发生了什么,请使用十六进制输出。
printf("%x\n", (unsigned) -1717986918); // UB to print a negative `int` with `"%x"`
printf("%a\n", 0.4);
9999999a
0x1.999999999999ap-2
所以看起来 0.4
有效数的最低 4 个字节被解释为 int
。
仍然是 UB。什么事都有可能发生。
最近,我在用 C 来测试不同的东西。
printf("%d", 0.4);
将打印 -1717986918。
我理解这一定与浮点数的二进制表示有关。但是,在使用一些在线资源将 0.4 转换为浮点数后,二进制表示与 -171986918 不匹配。请解释这段代码背后到底发生了什么。
PS:我在 Windows 64 位上使用 gcc 编译器 运行 它。
I understand that this must be related to the binary representation
不,这是未定义的行为 (UB)。
"%d"
与 double
不匹配。
If a conversion specification is invalid, the behavior is undefined. C17dr § 7.21.6.1 9
语言未定义 (UB) 输出和行为。什么事都有可能发生。
在某些系统上,UB 可能会看到二进制模式的一部分被解释为 int
。
在另一个系统上,int
和 double
以不同的方式传递,看到的输出基于垃圾。
在另一个系统或另一天,不好的 事情发生了。
都是未定义行为(UB)
explain what really happened
要了解 OP 的机器中可能发生了什么,请使用十六进制输出。
printf("%x\n", (unsigned) -1717986918); // UB to print a negative `int` with `"%x"`
printf("%a\n", 0.4);
9999999a
0x1.999999999999ap-2
所以看起来 0.4
有效数的最低 4 个字节被解释为 int
。
仍然是 UB。什么事都有可能发生。