简体   繁体   English

递归函数如何返回其值?

[英]How does recursive function return its value?

I'm trying to understand "Recursion" topic and i cant get how this recursive function return its argument after it leaves "if" provision. 我试图理解“递归”主题,但我不知道此递归函数如何在离开“ if”规定后返回其参数。

int sum(int x);
int main(){
    int num;
    printf("Enter a num : ");
    scanf("%d",&num);
    int result=sum(num);
    printf("Result : %d\n",result);
    return 0;
}
sum(int x){
    if (x > 4){
        return sum(x-1);
    }
}

For example, if i edit my "sum" function as "if (x>2)" it will return 2 value. 例如,如果我将“ sum”函数编辑为“ if(x> 2)”,它将返回2值。 Thats what im wondering. 那就是我想知道的。 Sum(2) doesnt have any value but it returns 2. Thanks! Sum(2)没有任何值,但返回2。谢谢!

 sum(int x){ if (x > 4){ return sum(x-1); } } 

does not return a value because a return is missing in the else branch and only that missing else branch finishes the recursion 不返回值,因为else分支中缺少返回值,只有该丢失的else分支完成了递归

i cant get how this recursive function return its argument after it leaves "if" provision. 我无法获得此递归函数在离开“ if”规定后如何返回其参数的信息。

Because of the missing return the behavior is undefined , if I do on my computer : 由于缺少返回,如果我在计算机上这样做,则行为是不确定的

pi@raspberrypi:/tmp $ ./a.out
Enter a num : 2
Result : 2
pi@raspberrypi:/tmp $ ./a.out
Enter a num : 12
Result : 4
pi@raspberrypi:/tmp $ ./a.out
Enter a num : 44
Result : 4

but the result can be anything else 但结果可能是其他任何事情

Your code does not compile as listed...and not returning from your sum function is causing undefined behavior. 您的代码未按列出的顺序进行编译...并且未从sum函数返回结果导致未定义的行为。 But more to your question, your recursion needs to eventually "bottom out". 但是,还有一个问题,您的递归最终需要“自下而上”。 There needs to be some scenario in which a "base case" is met and the function returns something other than itself. 在某些情况下,必须满足“基本情况”,并且该函数将返回自身以外的内容。 For example, try running the below code and see how x changes with different input... 例如,尝试运行以下代码,看看x如何随着不同的输入而变化...

#include <stdio.h>

int sum(int x);
int main() {
    int num;
    printf("Enter a num : ");
    scanf_s("%d", &num);
    int result = sum(num);
    printf("Result : %d\n", result);
    return 0;
}

int sum(int x) {
    if (x > 4) {
        printf("x is %d\n", x);
        return sum(x - 1);
    }
    return 10;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM