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


Question

How do I raise a number to a power?

2^1

2^2

2^3

etc...

1
105
5/10/2009 7:24:43 PM

Accepted Answer

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

126
6/18/2019 1:13:26 AM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon