问题
Hi I want to write a code for a pow function without using math.h libary.
How is this code?how can i fix it when b<0
int MyPow(int a,int b){
if(b<0)
return 1 / MyPow (a,-b)
else if(b==0)
return 1;
else if(b==1)
return a;
else
return a*MyPow(a,b-1)
}
回答1:
Everything seems perfect except for one condition :- when b<0
.
For b<0,simply return
return (1.0/a)*MyPow(a,abs(b)-1); //where abs(b) is absolute value of b.
OR
return (1.0/a)*(MyPow(a,b+1));
Also,your definition of function is not valid for performing negative exponentiation,you should change it to
float MyPow(int a,int b)
回答2:
Probably best way I think, found here
int pow(int base, int exp)
{
if(exp < 0)
return -1;
int result = 1;
while (exp)
{
if (exp & 1)
result *= base;
exp >>= 1;
base *= base;
}
return result;
}
回答3:
A solution with less complexity taken from http://www.geeksforgeeks.org/write-a-c-program-to-calculate-powxn/
float power(float x, int y)
{
float temp;
if( y == 0)
return 1;
temp = power(x, y/2);
if (y%2 == 0)
return temp*temp;
else
{
if(y > 0)
return x*temp*temp;
else
return (temp*temp)/x;
}
}
来源:https://stackoverflow.com/questions/25525536/write-pow-function-without-math-h-in-c