Reversing a five digit number with POW function in

2019-07-20 20:07发布

I have an exercise which demands a program that reverts a five digit number using pow, here is my try:

#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 type 12345 it returns 54320, the last digit is wrong! To check what was going on I enabled the printf comment an here it is a sample of execution:

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 50000 is converted to 49999, there is one less! And the weird part is that it only happens the first time, then for example 53999 is correctly converted to 53999. What is happening here?

标签: c reverse pow
2条回答
家丑人穷心不美
2楼-- · 2019-07-20 20:33

As the other commenters said, the issue is with rounding. pow() returns a double, and pow(10,4) must be returning a double close to 10000 but a bit or two off. Then in your print statement, when you print reversed + last_digit * pow( 10, counter ), this value is a double, close to 50000, but a bit off. When it prints, printf rounds to the precision you print to, so it prints as 50000. But when you assign to the integer reversed, the value is truncated, and if it is even one bit below 50000, it becomes 49999. Your teacher devised a very nice question - teaches nicely!

查看更多
倾城 Initia
3楼-- · 2019-07-20 20:44

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

查看更多
登录 后发表回答