and*_*wrk 356 c syntax printf format-specifiers long-long
#include <stdio.h>
int main() {
unsigned long long int num = 285212672; //FYI: fits in 29 bits
int normalInt = 5;
printf("My number is %d bytes wide and its value is %ul. A normal number is %d.\n", sizeof(num), num, normalInt);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
My number is 8 bytes wide and its value is 285212672l. A normal number is 0.
Run Code Online (Sandbox Code Playgroud)
我认为这个意想不到的结果是来自打印unsigned long long int
.你怎么printf()
了unsigned long long int
?
Joh*_*ney 459
将ll(el-el)long-long修饰符与u(无符号)转换一起使用.(适用于Windows,GNU).
printf("%llu", 285212672);
Run Code Online (Sandbox Code Playgroud)
Nat*_*man 85
您可能需要使用inttypes.h库,让你的类型,如尝试
int32_t
,int64_t
,uint64_t
等等,那么你可以使用它的宏,例如:
uint64_t x;
uint32_t y;
printf("x: %"PRId64", y: %"PRId32"\n", x, y);
Run Code Online (Sandbox Code Playgroud)
这是"保证"不给你同样的麻烦的long
,unsigned long long
等等,因为你不必去猜测有多少位是每个数据类型.
Shi*_*han 62
%d
- >为 int
%u
- >为 unsigned int
%ld
- >为 long int
%lu
- >为 unsigned long int
%lld
- >为 long long int
%llu
- >为 unsigned long long int
小智 38
对于使用MSVS的long long(或__int64),您应该使用%I64d:
__int64 a;
time_t b;
...
fprintf(outFile,"%I64d,%I64d\n",a,b); //I is capital i
Run Code Online (Sandbox Code Playgroud)
Pau*_*ves 36
这是因为%llu在Windows下无法正常工作,%d无法处理64位整数.我建议改用PRIu64,你会发现它也可以移植到Linux上.
试试这个:
#include <stdio.h>
#include <inttypes.h>
int main() {
unsigned long long int num = 285212672; //FYI: fits in 29 bits
int normalInt = 5;
/* NOTE: PRIu64 is a preprocessor macro and thus should go outside the quoted string. */
printf("My number is %d bytes wide and its value is %" PRIu64 ". A normal number is %d.\n", sizeof(num), num, normalInt);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
产量
My number is 8 bytes wide and its value is 285212672. A normal number is 5.
Run Code Online (Sandbox Code Playgroud)
Ada*_*rce 12
在Linux中,它就是%llu
在Windows中%I64u
虽然我发现它在Windows 2000中不起作用,但似乎有一个错误!
如何格式化
unsigned long long int
usingprintf
?
"ll"
由于 C99在转换说明符之前使用(ell-ell) o,u,x,X
。
许多答案中除了以 10 为基数的选项外,还有以 16 为基数和以 8 为基数的选项:
选择包括
unsigned long long num = 285212672;
printf("Base 10: %llu\n", num);
num += 0xFFF; // For more interesting hex/octal output.
printf("Base 16: %llX\n", num); // Use uppercase A-F
printf("Base 16: %llx\n", num); // Use lowercase a-f
printf("Base 8: %llo\n", num);
puts("or 0x,0X prefix");
printf("Base 16: %#llX %#llX\n", num, 0ull); // When non-zero, print leading 0X
printf("Base 16: %#llx %#llx\n", num, 0ull); // When non-zero, print leading 0x
printf("Base 16: 0x%llX\n", num); // My hex fave: lower case prefix, with A-F
Run Code Online (Sandbox Code Playgroud)
输出
Base 10: 285212672
Base 16: 11000FFF
Base 16: 11000fff
Base 8: 2100007777
or 0x,0X prefix
Base 16: 0X11000FFF 0
Base 16: 0x11000fff 0
Base 16: 0x11000FFF
Run Code Online (Sandbox Code Playgroud)