Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To the power of in C? [duplicate]

Tags:

c

math

So in python, all I have to do is

print(3**4)  

Which gives me 81

How do I do this in C? I searched a bit and say the exp() function, but have no clue how to use it, thanks in advance

like image 919
samir Avatar asked Sep 11 '13 05:09

samir


People also ask

How do you find the power of 2 in C?

Another solution is to keep dividing the number by two, i.e, do n = n/2 iteratively. In any iteration, if n%2 becomes non-zero and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2.

How do you calculate to the power of in C?

To calculate a power in C, the best way is to use the function pow() . It takes two double arguments: the first is the number that will be raised by the power, and the second argument is the power amount itself. So: double z = pow(double x, double y); Then the result will be saved into the double z.


2 Answers

You need pow(); function from math.h header.
syntax

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

Here x is base and y is exponent. result is x^y.

usage

pow(2,4);    result is 2^4 = 16. //this is math notation only    // In c ^ is a bitwise operator 

And make sure you include math.h to avoid warning ("incompatible implicit declaration of built in function 'pow' ").

Link math library by using -lm while compiling. This is dependent on Your environment.
For example if you use Windows it's not required to do so, but it is in UNIX based systems.

like image 188
Gangadhar Avatar answered Oct 06 '22 22:10

Gangadhar


you can use pow(base, exponent) from #include <math.h>

or create your own:

int myPow(int x,int n) {     int i; /* Variable used in loop counter */     int number = 1;      for (i = 0; i < n; ++i)         number *= x;      return(number); } 
like image 37
Ryan Webb Avatar answered Oct 06 '22 23:10

Ryan Webb