首页 > 解决方案 > 如何使用 printf 格式化(有符号)长整型?

问题描述

如何使用 printf 格式化(签名的)long long int?

#include <stdio.h>
int main() {
    long long int num = 123456766666666890; //FYI: fits in 29 bits
    int RegularInteger = 4;
    printf("My number is %d bytes wide and its value is %d. A normal number is %d.\n", sizeof(num), num, RegularInteger);
    return 0;
}

输出:

My number is 8 bytes wide and its value is 1917383562. A normal number is 4.                                                                                         

我没有得到想要的输出。

标签: c

解决方案


启用所有警告,一个好的编译器会警告不匹配的说明符并节省时间。

使用匹配的说明符。

使用 C99 或更高版本

#include <stdio.h>
int main() {
  long long int num = 123456766666666890; // A 57 bit number
  int RegularInteger = 4;

  // printf("My number is %d bytes wide",  sizeof(num));
  printf("My number is %zu bytes wide",  sizeof(num));

  // printf("and its value is %d.", num);
  printf("and its value is %lld.", num);

  printf(" A normal number is %d.\n", RegularInteger);
  return 0;
}

推荐阅读