Keep leading zeros when integer length is unknown

你说的曾经没有我的故事 提交于 2021-02-16 19:22:34

问题


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\n", 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

回答1:


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\n", (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.

[...]




回答2:


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

The integer text length can be known. Use "%n" to record the offset of the scan up to that point.


To reverse a string numerically (obviously a simple textual reversal is possible), record the length of the input.

When printing, insure leading zeros are pre-pended as needed using "%0*u".

int main(void) {
  int start, end;
  unsigned n;        // I prefer unsigned here, but could use int and %d below.
  printf("Enter an integer: ");
  fflush(stdout);
  //         v--- Consume leading white-space
  if (scanf(" %n%u%n", &start, &n, &end) == 1) {
    int length = end - start;
    unsigned reversedNumber = 0;
    for (int i = length; i > 0; i--) {
      unsigned remainder = n % 10;
      reversedNumber = reversedNumber * 10 + remainder;
      n /= 10;
    }
    printf("Reversed Number = %0*u\n", length, reversedNumber);
  }
  return 0;
}

Sample run

Enter an integer: 00123000
Reversed Number = 00032100



回答3:


Since the ultimate objective is to "add the digits of the original number starting from the second-to-last digit of the original number" why use characters (strings) at all -- just use numbers.

If I understand your question correctly:

/* test.c sum the digits of a number -- except for the last digit */

#include <stdio.h>

int main (void)
{
    int number;
    printf ("\nenter a number: ");
    scanf ("%i", &number);

    // power = multiple of 10 matching left-most digit in number
    // power is also a loop counter of sorts
    int power = 1;
    while ( number / power > 9 ) 
        power *= 10;    

    // process each digit moving from left to right across number
    // addition is commutative (order of digits does not affect result)

    int sum = 0;
    do {
        int digit = number / power;

        if ( power != 1 )           // skip last digit in number
            sum += digit;    

        number %= power;            // drop left-most digit from number
        power /= 10;                // adjust multiple of 10
    }
    while ( power > 0 );

    printf ("sum (skipping last digit) = %i\n", sum);

    return 0;
}



回答4:


You should use char array(string) for this because , its general mathematics rule we didn't consider zeros on left.

#include <stdio.h>
#include <string.h>
int main(){
    char value[]="3000";
    printf(" Number : %s ",value);
    char *rev=strrev(value);
    printf("Reversed Number = %s ",rev);
    return 0;
}


来源:https://stackoverflow.com/questions/50276364/keep-leading-zeros-when-integer-length-is-unknown

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