How does the function pow work?

前端 未结 2 1032
温柔的废话
温柔的废话 2021-01-23 04:52

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

#include
#include
int nr_cif(int a)
{         


        
相关标签:
2条回答
  • 2021-01-23 05:20

    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;
    }
    
    0 讨论(0)
  • 2021-01-23 05:27

    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.

    0 讨论(0)
提交回复
热议问题