该功能如何工作?

问题描述:

编译下面的程序后,我得到输出"2346",但期望是"2345".

After compiling the following program I get the output "2346" but was expecting "2345".

#include<math.h>
#include<iostream.h>
int nr_cif(int a)
{
    int k=0;
    while(a!=0)
    {
        a = a/10;
        k++;
    }
    return k;
}

void Nr(int &a){
    int k = nr_cif(a);
    a = a % (int)pow(10,k-1);
}


int main()
{
    int a = 12345;
    Nr(a);
    cout<<a;
}

调试之后,我注意到它在评估后会出错: a =%(int)pow(10,k-1).为什么会在这里破裂?

After debugging I noticed that it bugs out after it evaluates: a = a % (int)pow(10,k-1). Why does it break here?

使用pow进行整数数学并不是一个好主意.我将代码更改如下:

It's not a very good idea to use pow for integer math. I would change the code as follows:

void Nr(int &a)
{
    int ten_k = 1;
    while (ten_k < a) ten_k *= 10;
    a %= ten_k/10; // 10-to-the-(k-1)
}

您的代码中没有什么需要十进制数字,仅需要位数.因此,将地点值设为您的变量.

There's nothing in your code that needs the number of decimal digits, only the place value. So make the place value your variable.

(您也可以使用原始的while循环,该循环在负输入时效果更好.但是要计算并返回10到k的幂,而不是k).

(You could also use your original while loop, which works better for negative inputs. But calculate and return 10-to-the-k-power, instead of k).

pow的问题在于它可以处理浮点值,并给出非常接近但不精确的结果.该错误可能恰好足以导致舍入后的值(在转换为int之后)是错误的.您可以通过在强制转换前加0.5来解决此问题...但是没有意义,因为循环乘法比总而言之调用pow快.

The problem with pow is that it works with floating-point values, and gives results that are very close but not exact. The error might be just enough to cause the rounded value (after cast to int) to be wrong. You can work around that by adding 0.5 before casting... but there's no point, since multiplying in your loop is faster than calling pow anyway.