C语言 如何让数字在C中显示为两位数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14617865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:12:35  来源:igfitidea点击:

How do get numbers to display as two digits in C?

cdigit

提问by Adeel Anwar

For C programming. How do i get numbers to be displayed as 00, 01, 02, 03, instead of 0, 1, 2, 3. I just need 0 before the number until 10.

对于 C 编程。我如何让数字显示为 00、01、02、03,而不是 0、1、2、3。我只需要在数字之前加 0,直到 10。

i know when your doing decimals you can do "%.2f" etc. but what about in reverse for integers?

我知道当你做小数时,你可以做“%.2f”等,但反过来整数呢?

here is what I am using...**

这是我正在使用的...**

printf("Please enter the hours: ");
    scanf ("%d",&hour);
printf("Please enter the minutes: ");
    scanf ("%d",&minute);
printf("Please enter the seconds: ");
    scanf ("%d",&second);
printf("%d : %d : %d\n", hour, minute, second);

}

}

I need the numbers to display as 00 : 00 : 00

我需要数字显示为 00 : 00 : 00

??

??

回答by paxdiablo

You need to use %02dif you want leading zeroes padded to two spaces:

%02d如果要将前导零填充到两个空格,则需要使用:

printf ("%02d : %02d : %02d\n", hour, minute, second);

See for example the following complete program:

例如,请参阅以下完整程序:

#include <stdio.h>
int main (void) {
    int hh = 3, mm = 1, ss = 4, dd = 159;
    printf ("Time is %02d:%02d:%02d.%06d\n", hh, mm, ss, dd);
    return 0;
}

which outputs:

输出:

Time is 03:01:04.000159


Keep in mind that the %02dmeans two characters minimumwidth so it would output 123 as123. That shouldn't be a problem if your values are valid hours, minutes and seconds, but it's worth keeping in mind because many inexperienced coders seem to make the mistake that 2 is somehow the minimum andmaximum length.

请记住,这%02d意味着两个字符的最小宽度,因此它将输出 123作为123. 如果您的值是有效的小时、分钟和秒,那应该不是问题,但值得记住,因为许多没有经验的编码员似乎犯了一个错误,即 2 不知何故是最小最大长度。

回答by dreamlax

Use the format: %02dinstead. The 0means to pad the field using zeros and the 2means that the field is two characters wide, so for any numbers that take less than 2 characters to display, it will be padded with a 0.

使用格式:%02d代替。所述0垫装置使用零的字段和2表示该字段是两个字符宽,所以对于需要不到2个字符来显示任何数字,它将用0填充。