Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the C++ function to raise a number to a power?

Tags:

c++

math

People also ask

Is there a power function in C?

The pow() function is used to find the power of a given number. It returns x raised to the power of y(i.e. xy). The pow() function is present in math.

What is the code for power in C?

C pow() The pow() function computes the power of a number. The pow() function is defined in math. h header file.


pow() in the cmath library. More info here. Don't forget to put #include<cmath> at the top of the file.


std::pow in the <cmath> header has these overloads:

pow(float, float);
pow(float, int);
pow(double, double); // taken over from C
pow(double, int);
pow(long double, long double);
pow(long double, int);

Now you can't just do

pow(2, N)

with N being an int, because it doesn't know which of float, double, or long double version it should take, and you would get an ambiguity error. All three would need a conversion from int to floating point, and all three are equally costly!

Therefore, be sure to have the first argument typed so it matches one of those three perfectly. I usually use double

pow(2.0, N)

Some lawyer crap from me again. I've often fallen in this pitfall myself, so I'm going to warn you about it.


In C++ the "^" operator is a bitwise OR. It does not work for raising to a power. The x << n is a left shift of the binary number which is the same as multiplying x by 2 n number of times and that can only be used when raising 2 to a power. The POW function is a math function that will work generically.


You should be able to use normal C methods in math.

#include <cmath>

pow(2,3)

if you're on a unix-like system, man cmath

Is that what you're asking?

Sujal


Use the pow(x,y) function: See Here

Just include math.h and you're all set.