c

How do you do exponentiation in C?


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


Solution

  • use the pow function (it takes floats/doubles though).

    man pow:

       #include <math.h>
    
       double pow(double x, double y);
       float powf(float x, float y);
       long double powl(long double x, long double y);
    

    EDIT: For the special case of positive integer powers of 2, you can use bit shifting: (1 << x) will equal 2 to the power x. There are some potential gotchas with this, but generally, it would be correct.