【问题标题】:How do get numbers to display as two digits in C?如何让数字在C中显示为两位数?
【发布时间】:2023-04-02 06:53:01
【问题描述】:

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

我知道当你做小数时你可以做 "%.2f" 等等,但是对于整数呢?

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

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

}

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

??

【问题讨论】:

  • 一定是骗子吧?

标签: c digit


【解决方案1】:

"%.2d" 是应该使用的。 规则基本上是;

"%<minimum-characters-overall>.<minimum-digits>d".

例如:

"%6.3d" 将总共打印 6 个字符和至少 3 位数字。

【讨论】:

    【解决方案2】:

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

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

    例如看下面的完整程序:

    #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;
    }
    

    哪个输出:

    Time is 03:01:04.000159
    

    请记住,%02d 表示两个字符最小 宽度,因此它将输出 123 as 123。如果您的值是有效的小时、分钟和秒,这应该不是问题,但值得牢记,因为许多没有经验的编码人员似乎会错误地认为 2 是最小 最大长度。

    【讨论】:

    • 调整最大长度的解决方案是什么?
    • @rahman,指定最大长度没有好的解决方案。如果你有123 的值并且你把它硬塞到两位数,你会得到1223 之一,这取决于你决定如何去做。在我看来,这些都不可接受。最好输出 ** 来表示出现严重错误。
    【解决方案3】:

    请改用以下格式:%02d0 表示使用零填充该字段,2 表示该字段为两个字符宽,因此对于显示少于 2 个字符的任何数字,它将用 0 填充。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多