小编Sam*_*Sam的帖子

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

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

00015
   22
00111
    8
  126
Run Code Online (Sandbox Code Playgroud)

在这里,我需要leading spaces在数字evenleading zero时间打印odd

我是这样做的:

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);
}
Run Code Online (Sandbox Code Playgroud)

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

c printf

4
推荐指数
1
解决办法
7416
查看次数

标签 统计

c ×1

printf ×1