Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

c - Keep leading zeros when integer length is unknown

The following program reverses user input. However, for numbers with trailing zeroes, the zeroes are 'ignored' when printing the reversed number.

#include<stdio.h>

int main(void)
{
   int n, reversedNumber = 0, remainder;

    printf("Enter an integer: ");
    scanf("%d", &n);

    while(n != 0)
    {
        remainder = n%10;
        reversedNumber = reversedNumber*10 + remainder;
        n /= 10;
    }

    printf("Reversed Number = %d
", reversedNumber);

    return 0; 
}

Since the integer length of the user input is unknown, how can we print all the trailing zeros for example:

Enter an Integer: 3000 
Reversed Number = 0003

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

integer length is unknown

It isn't. :-)

Count the number of iterations and pass it to the final call to printf as width.

#include<stdio.h>

int main(void)
{
   int n, reversedNumber = 0, remainder;

   printf("Enter an integer: ");
   scanf("%d", &n);

   {
     size_t i = (0 > n);

     while (n != 0)
     {
       remainder = n % 10;
       reversedNumber = reversedNumber * 10 + remainder;
       n /= 10;
       ++i;
     }

     printf("Reversed Number = %0*d
", (int) i, reversedNumber); /* Alternatively
                                            to the cast you can define i as int. */
   }

   return 0; 
}

From the documentation:

4 Each conversion specification is introduced by the character %. After the %, the following appear in sequence:

[...]

  • An optional minimum field width. If the converted value has fewer characters than the field width, it is padded with spaces (by default) on the left (or right, if the left adjustment flag, described later, has been given) to the field width. The field width takes the form of an asterisk * (described later) or a nonnegative decimal integer.[...])

[...]

5 As noted above, a field width [...] may be indicated by an asterisk. In this case, an int argument supplies the field width or precision. The arguments specifying field width [...] shall appear (in that order) before the argument (if any) to be converted.

[...]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...