在 C 中使用 POW 函数反转五位数字 [英] Reversing a five digit number with POW function in C

查看:55
本文介绍了在 C 中使用 POW 函数反转五位数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个练习,需要一个使用 pow 还原五位数字的程序,这是我的尝试:

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

但是如果我输入 12345 它返回 54320,最后一位数字是错误的!为了检查发生了什么,我启用了 printf 注释,这是一个执行示例:

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

由于某种原因,前50000转换为49999,少了一个!奇怪的是,它只发生在第一次,然后例如 53999 正确转换为 53999.这里发生了什么?

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?

推荐答案

正如其他评论者所说,问题在于四舍五入.pow() 返回一个双精度值,而 pow(10,4) 必须返回一个接近 10000 的双精度值,但有一两个偏差.然后在你的打印语句中,当你打印 reversed + last_digit * pow( 10, counter ) 时,这个值是一个双精度值,接近 50000,但有点偏离.当它打印时,printf 四舍五入到你打印的精度,所以它打印为 50000.但是当你分配给整数 reversed 时,该值被截断,如果它甚至比 50000 低一位,它变成了 49999.你的老师设计了一个很好的问题——教得很好!

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!

这篇关于在 C 中使用 POW 函数反转五位数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆