int power( int base , int exponent )
{
if ( exponent == 1)
return 1 ;
else
return base *= power( base , exponent - 1 );
}
int main( )
{
cout << power( 3 , 4 ) << endl;
cout << pow( 3, 4 ) << endl; // Just for testing results
return 0;
}
Cheers
Edited by - StephenNitro on 10/15/00 2:59:08 PM
Recursive Function
I'm trying to build a function that does the same job as pow(x,y) the idea of the function is to learn recursion, however its not working, anyone now why?
Think about what is happening when you call the function. If you''re having trouble with a recursive function, write out what happens. For instance, your code does this:
Calling power(3,4)...
= 3 * power(3,3)
= 3 * 3 * power(3,2)
= 3 * 3 * 3 * power(3,1)
= 3 * 3 * 3 * 1
= 27 (wrong )
See the problem now? It''s your base case. When the exponent is 1, you would return ''base'' instead of returning 1. Or even better, use 0 as your base case, and return 1. That way your function will be able to handle a number raised the the 0th power, which is defined as 1. You should also add some functionality for negative powers, because as it stands, your function will recurse indefinitely if faced with a negative power, until your program crashes... which shouldn''t take too long.
-Ironblayde
Aeon Software
"Down with Nazrix!" -pouya -Ironblayde
Calling power(3,4)...
= 3 * power(3,3)
= 3 * 3 * power(3,2)
= 3 * 3 * 3 * power(3,1)
= 3 * 3 * 3 * 1
= 27 (wrong )
See the problem now? It''s your base case. When the exponent is 1, you would return ''base'' instead of returning 1. Or even better, use 0 as your base case, and return 1. That way your function will be able to handle a number raised the the 0th power, which is defined as 1. You should also add some functionality for negative powers, because as it stands, your function will recurse indefinitely if faced with a negative power, until your program crashes... which shouldn''t take too long.
-Ironblayde
Aeon Software
"Down with Nazrix!" -pouya -Ironblayde
"Your superior intellect is no match for our puny weapons!"
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement