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

我的梦境 提交于 2019-11-28 08:01:28

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

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 %02d means two characters minimum width so it would output 123 as 123. 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 and maximum length.

Use the format: %02d instead. The 0 means to pad the field using zeros and the 2 means 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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!