Home > Enterprise >  How can I truncate 0s from the end of numbers?
How can I truncate 0s from the end of numbers?

Time:10-06

I've written a C application that reverses the digits the user has input into the application.


Actual input:420

Actual output: 024


However, I'm looking to truncate 0 from the end of the number, if it exists.


Input:420

Expected output: 24


 #include <stdio.h>
 int main(void) {
 int x, s;
 scanf("%i",&x);

 for(int i = x; i > 0; ){
   s = i % 10;
   printf("%i", s); 
   i = i / 10;
    }

   return 0;
  }

CodePudding user response:

In this for loop

 for(int i = x; i > 0; ){
   s = i % 10;
   printf("%i", s); 
   i = i / 10;
    }

you are explicitly outputs zeroes if s is equal to 0.

Also if x is initially equal to 0 then nothing is outputted.

And if the entered number is negative then again nothing will be outputted that will confuse the user of the program.

One of approaches it to build a new number based on the entered number. For example

#include <stdio.h>

int main(void) 
{
    const int Base = 10;
    
    int x = 0;
    scanf( "%i", &x );
    
    long long int reverse = 0;
    
    do
    {
        reverse = Base * reverse   x % Base;
    } while ( x /= Base );
    
    printf( "%lld\n", reverse );
    
    return 0;
}

If to enter

-123456789

then the output will be

-987654321

CodePudding user response:

You can to this way, until you don't find the first non-zero number don't print.

#include <stdio.h>

int main(void) {
  int x, s;
  scanf("%i",&x);

  int first = 1;

  for(int i = x; i > 0; ){
    s = i % 10;

    if (first && s == 0){
      i = i / 10;
      if (i % 10 != 0)
        first = 0;
      continue;
    }

    printf("%i", s); 
    i = i / 10;
  }

  return 0;
}
  • Related