How do I raise a number to a power?
2^1
2^2
2^3
etc...
How do I raise a number to a power?
2^1
2^2
2^3
etc...
Use the pow(x,y) function: See Here
Just include math.h and you're all set.
It's pow or powf in <math.h>
There is no special infix operator like in Visual Basic or Python
pow(2.0,1.0)
pow(2.0,2.0)
pow(2.0,3.0)
Your original question title is misleading. To just square, use 2*2
.
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
While pow( base, exp )
is a great suggestion, be aware that it typically works in floating-point.
This may or may not be what you want: on some systems a simple loop multiplying on an accumulator will be faster for integer types.
And for square specifically, you might as well just multiply the numbers together yourself, floating-point or integer; it's not really a decrease in readability (IMHO) and you avoid the performance overhead of a function call.
Some lawyer crap from me again. I've often fallen in this pitfall myself, so i'm going to warn you about it. 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!
Therefor, be sure to have the first argument typed so it matches one of those three perfectly. I usually use double
pow(2.0, N)
I think, if you use the way which you know, it will be better.. here it is..
#include <math.h>
struct float_t
{
float value;
float_t(float v)
{
value = v;
}
operator float()
{
return value;
}
float operator ^(float c)
{
return powf(value, c);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
float_t num(4);
printf("%f", num ^ 3);
}