int power(int base, int exponent)
{
if (exponent >= 0)
{
int result = 1;
for (int i = 0; i < exponent; ++i)
{
result *= base;
}
return result;
}
else
{
throw std::exception("exponent < 0");
}
}
I think the fomula for negative exponent case is "1 / ( base ^ positive exponent )". I don't want to add a second for-loop, so this probably might be the best :
1 2 3 4 5 6 7 8 9
int a = 5; // base
int e = -3; // exponent
int p_e = abs(e); // exponent (positive) used with for-loop
double result = 1;
for (int i = 0;i < p_e;++i)result *= a;
if(e < 0)result = 1.0 / result;
elseif (exponent > 0)
{
int result = base; // make this a double to fix problem on next line
for (int i = 1; i < exponent; ++i) // result overflows if exponent > 32
{
result *= base;
}
return result;
}
With the negative exponent, I found it easier to do multiplication just as if the exponent was positive (use that code), then find the reciprocal at the end. There there is one division operation , and no casting.
The parameters to the function should both be const.
It would be a good idea to handle 00 and 0x where x < 0, which are undefined.
I got it to compile and run, but the result won't output on the console.
Line 31, you call the function but don't do anything with it - it needs to be assigned to a variable or the function call should be in the std::cout.
Line 31: std::pow is the library function. You have got away with here, only because you don't include <cmath> this is a very good reason not to have line 2.
Your code will overflow an int if exponent is greater than 32. You should check for this.
Lines 15 - 18 are unreachable because of the overlap with the test on line 6.
In function 'int pow(int, unsigned int)':
6:15: warning: comparison of unsigned expression >= 0 is always true [-Wtype-limits]
9:21: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
Always set the warning level for the compiler to it's highest.
It is very simple enough to begin with and all you need to do is insert cout << result; at the end. Modifying "a" or "e" will vary the result.
I'm certain that my example shouldn't contain either any possible warning or redundant code. To fully understand the logic behind it, you should test the simpler version first before you can try the more complex and complicated ones.
Of course, my example contains function abs() so you probably need to include <math.h> or <cmath.h>, just in case.