This code works fine, but when you use numbers which end with zero, the zero should be ignored. For instance, My code shows: input=420 output=024 How it is supposed to be: input=420 output=24
Thanks in advance!
#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;
}