What is the C++ function to raise a number to a power?
Solution 1:
pow() in the cmath library. More info here.
Don't forget to put #include<cmath>
at the top of the file.
Solution 2:
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.
Solution 3:
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.
Solution 4:
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
Solution 5:
Use the pow(x,y) function: See Here
Just include math.h and you're all set.