I made this program that asks a number and a power, and used a recursive function to get the answer. It all works except the function always returns 4, and I can't find out why.
#include <iostream>
usingnamespace std;
int a;
int b;
int c;
int power(int, int);
int main()
{
cout << "Enter number:\n";
cin >> a;
cout << "Power it by this positive number:\n";
cin >> b;
cout << "Answer: " << power(a, b) << "\n";
return 0;
}
int power(int base, int up)
{
if (up==1){ // A number to the power of 1 is the number
cout << "Returning... Base=" << base << " Up = " << up << "\n";
return base;}
else {
base = base*a;
up = up-1;
cout << "Did a multiplication... Base=" << base << " Up = " << up << "\n";
power (base, up);}
}
1. On line 26, why are you referring to a global variable (a)? Everything you need inside of the function definition has been passed in as a parameter.
2. On line 26, base is being modified before being passed to the recursive call on line 29.
3. On line 29, the function recurses, but it's returned value is not being captured (returned).
4. The power function would not handle a power of 0 appropriately.
5. Actually, I don't think you are even using the right algorithm to compute an exponential power. It should be more like this:
1 2 3 4 5 6 7 8 9 10 11
int power( int base, int up )
{
if( up == 0 )
{
return 1;
}
else
{
return base * power( base, --up );
}
}
6. Furthermore, I don't see any benefit to using a recursive solution for exponential powers when a simple loop would suffice. For example:
1 2 3 4 5 6 7 8 9
int power( int base, int up )
{
int ret = 1;
for( ; up > 0; --up )
{
ret *= base;
}
return ret;
}
1. I am referring to the global variable "a" because that is how powering a number works.
If you have 55 then you go
5 * 5 = 25 (52)
25 * 5 = 125 (53)
125 * 5 = 625 (54)
625 * 5 = 3125 (55)
in this example, the first number on each line would be "base". For each multiplication you multiply the "base" by 5 (5 is the global variable "a" that needs to stay the same).
2. Yep, that's true. For each multiplication the base changes. In the previous example the base goes from 5 to 25 to 125 to 625.
3. Thanks! Here is the problem, line 29 needed to be: return power (base, up);}
4. 0 isn't a positive number.
5. I must be doing it right because I get the correct answer.
6. True, but the exercise in the book I'm learning from said to try to use a recursive function to do it.
You dont understand Evan. You dont need to to reference the global variable because you have all of the variables in the scope of the function base and up.
@moor for your number 6. I think he was doing recursive for practice. In my class the teacher would come up with problems like this although much harder.