c - 为什么这个程序截断输出?

标签 c

我在下面的程序中做错了什么吗?

代码

    #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/

相关文章:

c - 如何将可变大小数组从 Windows 内核驱动程序传递到用户模式进程?

c - MPLAB X 中的有效代码和编译器错误

C - volatile 指针的使用

c++ - C或C++中是否有标准宏表示int32_t、int64_t的最大值和最小值?

c - 这个c程序是如何评估的

c - 如何在 Ubuntu 中使用 C 文件

c - 如何使用 fribidi 重新排序双向文本

c++ - 静态变量会阻碍数据缓存吗?

c - 优化 O(n^2) 到 O(n)(未排序的字符串)

c - 将 uint64_t 错误地传递给 va_list