我在下面的程序中做错了什么吗?
代码
#include <stdio.h>
int main()
{
long x=1290323123123;
int len = snprintf(NULL,0, "%ld", x);
printf("%ld %ld",x,len);
return 0;
}
输出: 1832934323 10
最佳答案
1290323123123 需要 41 位来存储,但是 long
可能只有 32 位长,所以多余的 9 位没有了。
1290323123123 = 0x12c6d405bb3
^^^
excessive data that is chopped off
= 0x6d405bb3
= 1832934323
使用
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
int main () {
int64_t x = 1290323123123LL;
// ^^^^^^^ ^^
int len = snprintf(NULL, 0, "%"PRId64, x);
// ^^^^^^^
printf("%"PRId64" %d\n", x, len);
// ^^^^^^^^
return 0;
}
确保类型至少为 64 位长,以便它可以完整地存储该值(结果:http://www.ideone.com/BnTjJ)。
关于c - 为什么这个程序截断输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4147681/