在 C/C++ 中打印前导空格和零 [英] Printing leading spaces and zeros in C/C++

查看:87
本文介绍了在 C/C++ 中打印前导空格和零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to print some leading spaces and zeros before a number, so that the output will be like this:

00015
   22
00111
    8
  126

这里,当数字为偶数前导零时,我需要打印前导空格odd

here, I need to print leading spaces when the number is even and leading zero when 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);
}

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

Is there any shortcut way to do this ?

推荐答案

要打印前导空格和零,您可以使用:

int x = 119, width = 5;

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

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

所以在你的程序中只需改变这个:

So in your program just change this :

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);

这篇关于在 C/C++ 中打印前导空格和零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆