我有一个简单的C ++递归问题。在我问我的问题之前,我认为最好展示一下我所拥有的代码。

void message(int times)
{
  if (times > 0)
  {
    cout << "This is a recursive function" << endl;
    message(times - 1);
  }
  cout << "message returning with " << times << " in times << endl;
}


让整数变量时间设置为5。
这是该函数的输出

This is a recursive function
This is a recursive function
This is a recursive function
This is a recursive function
This is a recursive function
Message called with 0 in times
Message called with 1 in times
Message called with 2 in times
Message called with 3 in times
Message called with 4 in times
Message called with 5 in times


我知道为什么输出语句“这是一个递归函数”,但我不明白为什么输出语句“消息以0-5多次调用”?谢谢

最佳答案

让我们看一小段代码:

    message(times - 1);
}
cout << "message returning with " << times << " in times << endl;


您认为此函数调用message()返回后会发生什么?您确实知道,当您调用函数时,一旦函数调用返回,则调用者将继续执行下一条语句,对吗?

这就是这里发生的情况。因此,例如,当调用此代码并为5的值传递times时,这就是您最终看到的消息。

我敢肯定,无论使用哪种编译器,您都应该有一个随附的调试器工具,该工具可让您在执行程序时一次一行地完成程序。如果您花时间学习如何使用调试器,则可以将其与程序一起使用,并亲自了解每一行的执行方式以及执行原因。

关于c++ - 递归:输出特定文本的原因?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36440176/

10-11 22:06
查看更多