开发者社区 问答 正文

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;
}

展开
收起
a123456678 2016-06-07 19:43:23 1912 分享 版权
1 条回答
写回答
取消 提交回答
  • 你的递归函数里没有结束递归的条件啊?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;
    }
    2019-07-17 19:30:52
    赞同 展开评论