在 C/C++ 中打印前导空格和零

Printing leading spaces and zeros in C/C++

我需要在数字前打印一些前导空格和零,以便输出如下所示:

00015
   22
00111
    8
  126

这里,我需要在数字为even时打印leading spaces,在odd

时打印leading zero

我是这样做的:

int i, digit, width=5, x=15;

if(x%2==0)  // number even
{
    digit=log10(x)+1;  // number of digit in the number
    for(i=digit ; i<width ; i++)
      printf(" ");
    printf("%d\n",x);
}
else       // number odd
{
    digit=log10(x)+1;  // number of digit in the number
    for(i=digit ; i<width ; i++)
      printf("0");
    printf("%d\n",x);
}

有没有捷径可以做到这一点?

要打印 leading space and zero 你可以使用这个:

int x = 119, width = 5;

// Leading Space
printf("%*d\n",width,x);

// Leading Zero
printf("%0*d\n",width,x);

因此在您的程序中只需更改此:

int i, digit, width=5, x=15;

if(x%2==0)  // number even
    printf("%*d\n",width,x);
else        // number odd
    printf("%0*d\n",width,x);