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;
}

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

有帮助吗?

解决方案

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.

(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).

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.

其他提示

I'm not amazing or great at math but this seems to work: http://ideone.com/dFsODB

#include <iostream>
#include <cmath>

float mypow(float value, int pow)
{
    float temp = value;
    for (int i = 0; i < pow - 1; ++i)
        temp *= value;

    for (int i = 0; i > pow - 1; --i)
        temp /= value;

    return temp;
}


int main() 
{
    std::cout<<pow(10, -3)<<"\n";
    std::cout<<mypow(10, -3)<<"\n";
    return 0;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top