pow() seems to be out by one here

前端 未结 4 478
青春惊慌失措
青春惊慌失措 2020-12-01 13:26

What\'s going on here:

#include 
#include 
int main(void) {
    printf(\"17^12 = %lf\\n\", pow(17, 12));
    printf(\"17^13 = %l         


        
4条回答
  •  渐次进展
    2020-12-01 14:18

    If your input arguments are non-negative integers, then you can implement your own pow.

    Recursively:

    unsigned long long pow(unsigned long long x,unsigned int y)
    {
        if (y == 0)
            return 1;
        if (y == 1)
            return x;
        return pow(x,y/2)*pow(x,y-y/2);
    }
    

    Iteratively:

    unsigned long long pow(unsigned long long x,unsigned int y)
    {
        unsigned long long res = 1;
        while (y--)
            res *= x;
        return res;
    }
    

    Efficiently:

    unsigned long long pow(unsigned long long x,unsigned int y)
    {
        unsigned long long res = 1;
        while (y > 0)
        {
            if (y & 1)
                res *= x;
            y >>= 1;
            x *= x;
        }
        return res;
    }
    

提交回复
热议问题