How do you do exponentiation in C?
use the pow
function (it takes float
s/double
s 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.
To add to what Evan said: C does not have a built-in operator for exponentiation, because it is not a primitive operation for most CPUs. Thus, it's implemented as a library function.
Also, for computing the function e^x, you can use the exp(double)
, expf(float)
, and expl(long double)
functions.
Note that you do not want to use the ^
operator, which is the bitwise exclusive OR operator.