首页 > C语言利用递归实现整数次幂出错

C语言利用递归实现整数次幂出错

#include <stdio.h>
#include <stdlib.h>

int show(int number,int count);
int main()
{
    int count;
    int number;
    while(scanf("%d%d",&number,&count)==2){
        if(number==0){
            printf("the answer is 0");
        }
        else{
            if(count==0){
                printf("the answer is 1");
            }
            if(count>0){
                printf("the answer is %d\n",show(number,count));
            }
        }
        printf("please try again:");
    }
    return 0;
}
int show(int number,int count){
    if(count>0)
        return show(number,(count-1))*number;
}

它的运行结果不对,查了好久看不出来为什么。

更奇怪的是把上述所有类型换成double以后,乱码了

#include <stdio.h>
#include <stdlib.h>

double  show(double  number,double count);
int main()
{
    double count;
    double number;

    while(scanf("%lf%lf",&number,&count)==2){
        if(number==0){
            printf("the answer is 0");
        }
        else{
            if(count==0){
                printf("the answer is 1");
            }
            if(count>0){
                printf("the answer is %f\n",show(number,count));
            }
        }
        printf("please try again:");
    }
    return 0;
}
double show(double number,double count){
    if(count>0)
        return show(number,(count-1))*number;
}

运行结果:


你的递归函数里没有结束递归的条件啊?count>0的时候会不断往你的最终结果里面添加乘数因子,那么到count=0了之后呢?不是应该指定返回一个1吗?这样才能结束递归调用。

int show(int number,int count){
    if(count>0)
        return show(number,(count-1))*number;
    else if(count==0)
        return 1;
}

这样一来,main函数里面单独给count=0的情况写一个if分支也是不需要的,因为它只能判断初始输入值,无法判断递归执行过程中,count递减到哪个值了——还不如凡是count>=0正确就统一留到show()函数里面来判断。

int main()
{
    int count;
    int number;
    while(scanf("%d%d",&number,&count)==2){
        if(number==0){
            printf("the answer is 0");
        }
        else{
            if(count>=0){
                printf("the answer is %d\n",show(number,count));
            }
        }
        printf("please try again:");
    }
    return 0;
}

没有递归结束的判定
int show(int number,int count){
if(count == 1)
return number;
else
return show(number,(count-1))*number;
}

【热门文章】
【热门文章】