How do you do exponentiation in C?

前端 未结 7 1506
执笔经年
执笔经年 2020-12-05 06:31

I tried \"x = y ** e\", but that didn\'t work.

7条回答
  •  情书的邮戳
    2020-12-05 06:56

    The non-recursive version of the function is not too hard - here it is for integers:

    long powi(long x, unsigned n)
    {
        long p = x;
        long r = 1;
    
        while (n > 0)
        {
            if (n % 2 == 1)
                r *= p;
            p *= p;
            n /= 2;
        }
    
        return(r);
    }
    

    (Hacked out of code for raising a double value to an integer power - had to remove the code to deal with reciprocals, for example.)

提交回复
热议问题