我写了一小段C代码。
#include<stdio.h>
int main()
{
int a = 0;
printf("Hello World %llu is here %d\n",a, 1);
return 0;
}
它正在打印以下输出
Hello World 4294967296 is here -1216225312
编译时有如下警告
prog.cpp: In function ‘int main()’:
prog.cpp:5: warning: format ‘%llu’ expects type ‘long long unsigned int’, but argument 2 has type ‘int’
我知道我需要将 int 转换为 long long unsigned int,但我不明白为什么后来的值被破坏了。
提前致谢
最佳答案
%llu 需要一个 64 位整数。但是你只给了它一个 32 位整数。
效果是 printf 正在读取的内容相对于您传递的内容“移动”了 32 位。因此,您的“1”没有在正确的位置被读取。
编辑:
现在解释输出:
a
和 1
被分开存储 32 位,因为它们都是 32 位整数。
但是,printf 期望第一个参数是 64 位整数。因此它将它读作 a + 2^32 * 1
在您的情况下是 4294967296
。打印的第二个值未定义,因为它超过了 1
。
关于c++ - printf 没有打印正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7329840/