c/c++语言开发共享用C / C ++打印前导空格和零

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

00015 22 00111 8 126 

在这里,我需要在数字为even时打印leading spaces ,在oddleading 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("%dn",x); } else // number odd { digit=log10(x)+1; // number of digit in the number for(i=digit ; i<width ; i++) printf("0"); printf("%dn",x); } 

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

    要打印leading space and zero您可以使用:

     int x = 119, width = 5; // Leading Space printf("%*dn",width,x); // Leading Zero printf("%0*dn",width,x); 

    所以在你的程序中只需更改:

     int i, digit, width=5, x=15; if(x%2==0) // number even printf("%*dn",width,x); else // number odd printf("%0*dn",width,x); 

      以上就是c/c++开发分享用C / C ++打印前导空格和零相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/544914.html

      (0)
      上一篇 2021年1月9日
      下一篇 2021年1月9日

      精彩推荐