在C中打印前导0 [英] Printing leading 0's in C
问题描述
I'm trying to find a good way to print leading 0
, such as 01001
for a ZIP Code. While the number would be stored as 1001
, what is a good way to do it?
我想到了使用 case
语句或 if
找出数字是多少位数,然后将其转换为 char
数组带有额外的 0
进行打印,但是我不禁想到,可能有一种方法使 printf
格式的语法难以理解.>
I thought of using either case
statements or if
to figure out how many digits the number is and then convert it to an char
array with extra 0
's for printing, but I can't help but think there may be a way to do this with the printf
format syntax that is eluding me.
推荐答案
printf("%05d", zipCode);
0
表示要填充的内容, 5
表示整数的宽度.
The 0
indicates what you are padding with and the 5
shows the width of the integer number.
示例1:如果使用%02d"
(对日期有用),则只会在一"列中填充数字零.例如 06
而不是 6
.
Example 1: If you use "%02d"
(useful for dates) this would only pad zeros for numbers in the ones column. E.g., 06
instead of 6
.
示例2:%03d"
将在one列中填充2个零以表示一个数字,在tens列中填充1个零以表示一个数字.例如,将7号填充到 007
中,将17号填充到 017
中.
Example 2: "%03d"
would pad 2 zeros for one number in the ones column and pad 1 zero for a number in the tens column. E.g., number 7 padded to 007
and number 17 padded to 017
.
这篇关于在C中打印前导0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!