C语言 用递归函数求数值的整数次幂 double power(double x,int p)输入负整数次幂时出现问题
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 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.52的-3次幂还是0.5一直都是0.5..
最佳回答
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,因为你调用负数求幂,必须使参数为负才会正确
最新回答共有2条回答
-
2026-04-08 03:55:02勤恳的向日葵
回复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,因为你调用负数求幂,必须使参数为负才会正确
热门文章
- 康达学院专转本五年制
- 高考一个考场分ab卷吗
- not only but also用法
- 某物体做自由落体运动,从释放开始计时,则物体在前2s内的平均速度为______m/s,物体下落2m时的速度大小为______m/s.
- 三角函数公式大全表格
- 地理中考必背知识点2022
- 2013-2014学年小学六年级科学上学期期末考试试卷及答案
- 人教版2014-2015学年小学五年级英语第二学期期中教学质量检测试卷及答案
- 【Linux驱动开发】设备树详解(二)设备树语法详解
- 别跟客户扯细节
- 在别的城市买房子能落户吗
- 卖房前要把装修贷还完吗
- 高中政治教学提高教学效果的方法探究
- “互联网+”背景下的初中英语课堂教学改革与创新策略研究
- 2022年终止合同范本
- 租房合同范本范文
- 如何挑选土豆
- 如何挑选土鸡
