Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you do exponentiation in C?

Tags:

c

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

like image 302
raldi Avatar asked Oct 17 '08 17:10

raldi


People also ask

How do you do exponential in C?

Basically in C exponent value is calculated using the pow() function. pow() is function to get the power of a number, but we have to use #include<math. h> in c/c++ to use that pow() function.


1 Answers

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.

like image 56
Evan Teran Avatar answered Nov 02 '22 14:11

Evan Teran