How does the function pow work?

北慕城南 提交于 2019-12-02 05:30:50

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/22737681/how-does-the-function-pow-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!