用递归函数求数值的整数次幂
代码如下:#include<stdio.h>
double power_positive(double n,int p);
double power_negative(double n,int p);
int main(void)
{
double x,xpow;
int exp;
printf("Enter a number and the integer power to which\n");
printf("the number will be raised.Enter q to quit.\n");
while(scanf("%lf %d",&x,&exp)==2)
{
if(x==0)
printf("%lf to the power of %d is 0.\n",x,exp);
else if(exp==0)
printf("%lf to the power of %d is 1.\n",x,exp);
else if(exp>0)
{
xpow=power_positive(x,exp);
printf("%lf to the power of %d is %lf.\n",x,exp,xpow);
}
else
{
xpow=power_negative(x,exp);
printf("%lf to the power of %d is %lf.\n",x,exp,xpow);
}
printf("Enter next pair of numbers or q to quit.\n");
}
printf("Hope you enjoyed this power trip --BYE!\n");
return 0;
}
double power_positive(double n,int p)
{
double pow=1;
if(p>0)
pow=n*power_positive(n,(p-1));
return pow;
}
double power_negative(double n,int p)
{
double pow = 1;
int q;
q=-p;
if(q>0)
pow = power_negative(n,1-q) / n;
return pow;
}
}