我有一个简单的 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;
}
设整型变量times设为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
我明白为什么会输出“This is a recursive function”,但不明白为什么会输出“Message called with 0-5 in times”?谢谢
最佳答案
让我们看一下您的一小部分代码:
message(times - 1);
}
cout << "message returning with " << times << " in times << endl;
您认为对 message() 的函数调用返回后会发生什么?您确实知道,当您调用一个函数时,一旦函数调用返回,调用者就会继续执行下一条语句,对吧?
这正是这里发生的事情。因此,当调用此代码时传递 5
作为 times
的值,这就是您最终看到的消息。
我敢肯定,无论您使用的是什么编译器,您都应该拥有一个配套的调试器工具,它可以让您在程序执行时逐步执行程序,一次一行。如果您花时间学习如何使用调试器,则可以将其用于您的程序,并亲眼看看每一行的执行方式和原因。
关于c++ - 递归:输出指定文本的原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36440176/