cmath

To the power of in C?


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.


Solution

  • 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.