printf的显示器很奇怪 [英] printf displays something weird

查看:212
本文介绍了printf的显示器很奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有这样code:

#include <stdio.h>

int main() {
  float d = 1.0;
  int i = 2;
  printf("%d %d", d, i);
  getchar();
  return 0;
}

和输出是:

0 1072693248

我知道有printf和首次%d个错误应该以%F取代。但是,为什么变量i印错(的1072693248而不是2)?

I know that there is error in printf and first %d should be replaced with %f. But why variable i is printed wrong (1072693248 instead of 2)?

推荐答案

既然你指定的%d个而不是%F ,你真正看到的是 D 的二进制重新presentation为整数。

Since you specified %d instead of %f, what you're really seeing is the binary representation of d as an integer.

此外,由于数据类型不匹配,code实际上是未定义行为。

Also, since the datatypes don't match, the code actually has undefined behavior.

编辑:

现在来解释为什么你没有看到 2

Now to explain why you don't see the 2:

浮动提升为双击在堆栈中。键入双击是(在本例中)8个字节长。然而,由于你的的printf 指定两个整数(在这种情况下,两个4字节),你看到的的二进制重新presentations 1.0 作为一种双击。 2.不打印,因为它超出了8个字节,你的的printf 预计。

float gets promoted to double on the stack. Type double is (in this case) 8 bytes long. However, since your printf specifies two integers (both 4 bytes in this case), you are seeing the binary representations of 1.0 as a type double. The 2 isn't printed because it is beyond the 8 bytes that your printf expects.

这篇关于printf的显示器很奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆