成都网站建设设计

将想法与焦点和您一起共享

c语言用递归函数求负次幂 c语言用递归方式求n!

C语言 用递归函数求数值的整数次幂 double power(double x,int p)输入负整数次幂时出现问题

double power_negative(double n,int p)

蚌埠网站制作公司哪家好,找创新互联建站!从网页设计、网站建设、微信开发、APP开发、响应式网站建设等网站项目制作,到程序开发,运营维护。创新互联建站于2013年创立到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联建站

{

double pow = 1;

int q;

q=-p;

if(q0)

pow = power_negative(n,1-q) / n;

return pow;

}

改成这样,虽然你那个写的是递归调用,但是返回的却是1/pow,那么就会是0.5 * 2 * 0.5 * 2 * 0.5这样的形式返回,所以最终无论是多少,结果都是0.5,而且递归时应该用1-q,因为你调用负数求幂,必须使参数为负才会正确

c语言递归函数实现某数次幂的运算

long

double

_pow_i(

long

double

_X,

int

_Y

)

{

if

(

!_Y

)

return

1;

//

次幂为0的情况

if

(

!(_Y-1)

)

return

_X;

//

当_Y

1的情况则返回结果_X

return

_X

*

_pow_i(

_X,

abs(_Y)-1

);

//

每一步返回

_X

*

上一次的乘积,_Y

减1计数

}

long

double

_pow(

long

double

_X,

int

_Y

)

{

long

double

_Z

=

_pow_i(

_X,

_Y

);

return

_Y

?

1

/

_Z

:

_Z;

}

因为写在一起的话不好解释,所以分开正负的情况,_pow就是判断次幂是否为负数,是负数就等于1/那个数个正次幂。

C语言递归计算正负幂

#includestdio.h

double power(double x,int n)

{if(n==0)return 1.0;

else if(n0)return x*power(x,n-1);

else return power(x,n+1)/x;

}

int main()

{double x;

int n;

scanf("%lf%d",x,n);

printf("%lf\n",power(x,n));

return 0;

}

C语言 用递归函数求数值的整数次幂 double power(double x,int p).在求数值的负数次幂时出现问题。

#includestdio.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 (exp0)

{

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 (p0)

pow=n*power_positive(n,(p-1));

return pow;

}

double power_negative(double n,int p) //用递归实现

{

if (p==-1)return 1/n;

else

return (1/n)*power_negative(n,p+1);

}


文章标题:c语言用递归函数求负次幂 c语言用递归方式求n!
URL标题:http://chengdu.cdxwcx.cn/article/dojgccs.html