【问题标题】:How can i solve the following code? [duplicate]我该如何解决以下代码? [复制]
【发布时间】:2012-08-31 15:03:10
【问题描述】:

可能重复:
What is recursion really and explain the output of this program?
What is really happening in this code?

我有一个我不明白的递归函数。我什至不知道代码是否有效:

int count(int x) // suppose x is 3
{
  if(x>0)
  {
    count(--x);
    printf(x);
    count(--x);  // control reaches here or not?
  }
}

这只是伪代码。取初始变量为3。请结合上下文解释堆栈的概念。这段代码让我困惑了好几天,我真的找不到这段代码的答案。

【问题讨论】:

  • 显然这是一个很多的家庭作业,因为许多新手都在问同样的问题。最好的建议是阅读一本关于递归的好书。不可能在几分钟内向不知名的观众解释。
  • 请注意,您不会从非 void 函数返回任何内容。那是未定义的行为。
  • 在 SO 中搜索递归并找到针对这个确切问题的其他一些答案。有很多好的。如果您仍然不明白,请参考那些更新您的问题。
  • 我会让代码可编译并放入更多 printf 语句以查看发生了什么。执行该方法,看看它是如何调用自己的。
  • 我真的很想知道谁在做这个作业。这是一段愚蠢的代码,显然很多学生不明白..

标签: c function recursion operators


【解决方案1】:

好的,只是因为我需要稍微唤醒我的大脑:-)

count(3) 将进入函数并调用count(2)(第二级)。
count(2) 将进入函数并调用count(1)(第三级)。
count(1)将进入函数并调用count(0)(第4层)。
count(0)将进入函数,但由于x>0为假,它不会做任何事情,只是返回到第4层x 仍为 0。

第4级会输出0,调用count(-1)(第5级)

count(-1) 将进入函数,但由于x>0 为假,它不会做任何事情,只是返回到x 仍然为-1 的第4 层。
第 4 级返回到第 3 级,x 仍为 1。

第三级会输出1并调用count(0)(第四级)

count(0) 将进入函数,但由于x>0 为假,它不会做任何事情,只是返回到x 仍为0 的3:rd 级别。
3:rd 级别返回到 2:nd 级别,x 仍为 2。

第二级会输出2并调用count(1)(第三级)

count(1) 将进入函数并调用count(0) (4:th level)。
count(0) 将进入函数,但由于x>0 为假,它不会做任何事情而只是返回到x 仍然为0 的3:rd 级别。

第三级会输出0并调用count(-1)(第四级)

count(-1) 将进入函数,但由于x>0 为假,它不会做任何事情,只是返回到x 仍然为-1 的第三层。

第 3 级返回到第 2 级,此时 x 仍为 1。
2:nd 级别返回 1:st 级别,我们完成了。

输出为0 1 2 0

我建议如果你真的想明白这一点,自己用count(4)试试吧。

【讨论】:

    【解决方案2】:

    这个函数根本不会返回任何东西。在过去的几天里,我已经看到这个问题在这里发布了很多次。以下是一些与 cmets 一起工作的代码,可帮助您理解:

    /*function declaration so that the program can utilize it*/
    int count(int x);
    
    /*main routine that calls the function*/
    int main(void)
    {
        count(3);    //call the function
        return 0;
    }      
    
    /*function prototype*/
    int count(int x)
    {
        if(x > 0)
        {
             printf("%d", x - 1); //print the value of x - 1 to the screen 
             return count(--x);   //Have the function call itself again with a new argument (the value of x after being decremented)
        }
        return x;                 //x is no longer greater than 0 so return it's value
    }
    

    请注意此示例中return 的使用,并阅读return 的作用。 现在这只是一些更正的代码。了解递归函数在做什么的最好方法(在我看来)是在纸上草拟出来。

    【讨论】:

    • 这与伪代码不同。是的,您发布了有效代码,它比 Amol Singh 的功能更“计数”,但这不是问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 2013-10-09
    • 2020-06-23
    • 1970-01-01
    • 2020-06-26
    • 2021-08-19
    • 2020-10-03
    相关资源
    最近更新 更多