#include<iostream>
usingnamespace std;
float pow(float,int);
int main()
{
cout<<pow(10,-2);
}
float pow(float a, int b)
{
if(b==0)
return 1;
elseif(b==1)
return a;
elseif(b>1)
return a*pow(a,b-1);
if(b==-1)
return 1/a;
if(b<-1)
{
a*=pow(a,b+1);
return 1/a;
}
}
I just cant figure out how to return 1/a ONCE in the base case instead of getting 1/a on each stack phase. i know what i wrote returns wrong value. if there was a better way to compute the number when powered by negative number please enlight me :)
Thanks
Just as you multiply by a for the case b>1 on line 19, you should divide by b for the b<1 case.
In any case I think you have over complicated the treatment. For example, you treat the case
b == 1 explicitly, even though one recursive step will take it to the b=0 case, which is handled already. You should need only the one terminating case.
I got this for the function myself. It seems to work:
1 2 3 4 5 6
float myPow( float b, int e )// using b=base and e=exponent = less confusion for me
{
if( e == 0 ) return 1.0f;// terminates the recursion
if( e > 0 ) return myPow( b, e-1 )*b;
if( e < 0 ) return myPow( b, e+1 )/b;
}
EDIT: Note there is no need for the 'else if' because of the return encountered in the 'if' parts of the code. The return prevents the other if's from executing.