Reversing a Five-Digit Number with the POW Function in C

I have an exercise that requires a program that returns a five-digit number using pow, here is my attempt:

#include <math.h> #include <stdio.h> void main( void ) { int number, counter = 0, last_digit, reversed = 0; printf( "Please type a five digit number and I will reverse it\n" ); scanf( "%d", &number ); for( counter = 4; counter >= 0; counter-- ) { last_digit = number % 10; number = number / 10; //printf( "%d %d %.0f %.0f\n\n", reversed, last_digit, pow ( 10, counter ), reversed + last_digit * pow( 10, counter )); reversed = reversed + last_digit * pow( 10, counter ); }//end for printf( "The number reversed is %d", reversed ); }//end main 

But if I dial 12345, it will return 54320, the last digit is incorrect! To check what happens, I included the printf comment here, this is a sample run:

 Please type a five digit number and I will reverse it 12345 0 5 10000 50000 49999 4 1000 53999 53999 3 100 54299 54299 2 10 54319 54319 1 1 54320 The number reversed is 54320 

For some reason, the first 50,000 is converted to 49999, there is one less! And the strange part is that this happens only for the first time, then, for example, 53999 is correctly converted to 53999. What happens here?

+2
c reverse pow
Sep 06 '14 at 0:27
source share
2 answers

As other commentators have said, the problem is rounding. pow() returns double, and pow(10,4) should return double, close to 10000, but a bit or two. Then in your print statement, when you type reversed + last_digit * pow( 10, counter ) , this value is double, close to 50,000, but a little off. When it prints, printf rounds to the precision that you print, so it prints 50,000. But when you assign the integer reversed , the value is truncated, and if it is one bit lower than 50,000, it becomes 49999. Your teacher has developed a very good question - teaches beautifully!

+1
Sep 06 '14 at 1:03
source share

You can use round (pow (10, counter))

+1
Sep 06
source share



All Articles