简体   繁体   English

printf格式

[英]printf formatting

我想使用printf0x###的形式显示十六进制数字,但是如果数字为0,我想省略0x部分。

printf("%#x", number);

Note that this does exactly what you want. 请注意,这正是您想要的。 If the value of number is 0, it prints 0, otherwise it prints in hex. 如果number的值为0,则打印0,否则以十六进制打印。 Example: 例:

int x = 0;
int y = 548548;

printf("%#x %#x\n", x, y);

Results in: 结果是:

0 0x85ec4
 printf ((x == 0) ? "%03x" : "0x%03x", x);
if (num == 0)
{
     printf("0");
}
else
{
     printf("%X", num);
}

Why make it hard? 为什么要加倍努力?

if number = 0
  printf without formatting
else
  printf with formatting

您不能只使用if语句来检查数字是否为0,然后弄清楚是否应该将其打印为0x ###或仅打印000(或者如果要查找则打印为0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM