C语言 用递归函数求数值的整数次幂 double power(double x,int p)输入负整数次幂时出现问题代码如下:#includedouble power_positive(double n,int p);double power_negative(double n,int p);int main(void){double x,xpow;int ex
来源:学生作业帮助网 编辑:六六作业网 时间:2024/11/18 01:28:45
C语言 用递归函数求数值的整数次幂 double power(double x,int p)输入负整数次幂时出现问题代码如下:#includedouble power_positive(double n,int p);double power_negative(double n,int p);int main(void){double x,xpow;int ex
C语言 用递归函数求数值的整数次幂 double power(double x,int p)输入负整数次幂时出现问题
代码如下:
#include
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;
double re;
int q;
q=-p;
if(q>0)
pow=n*power_negative(n,q-1);
re=1/pow;
return re;
}
可以运行.编译不报错.但是输入负整数次幂时计算结果根本就不对.也不知道错到哪里了.请高人指教哈.
比如说2的-2次幂是0.5
2的-3次幂还是0.5
一直都是0.5..
C语言 用递归函数求数值的整数次幂 double power(double x,int p)输入负整数次幂时出现问题代码如下:#includedouble power_positive(double n,int p);double power_negative(double n,int p);int main(void){double x,xpow;int ex
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;
}
改成这样,虽然你那个写的是递归调用,但是返回的却是1/pow,那么就会是0.5 * 2 * 0.5 * 2 * 0.5这样的形式返回,所以最终无论是多少,结果都是0.5,而且递归时应该用1-q,因为你调用负数求幂,必须使参数为负才会正确