[英]Regarding Recursive Functions in C++ (Beginner Level)
因此,我才刚刚开始C ++编程,并且对用于演示递归函数如何工作的特定程序有些困惑。 我确实知道递归函数的前提,即递归函数的调用直到满足退出条件为止。 我了解了使用阶乘程序的概念,
int factorial(int n)
{
if (n==1)
{
return 1;
}
else
{
return n*factorial(n-1);
}
}
if语句是以上代码中的退出条件。
但是,令我震惊的代码来自以下链接: http : //www.cprogramming.com/tutorial/lesson16.html
具体来说这段代码:
#include <iostream>
using namespace std;
void printnum ( int begin )
{
cout<< begin<<endl;
if ( begin < 9 ) // The base case is when begin is greater than 9
{ // for it will not recurse after the if-statement
printnum ( begin + 1 );
}
cout<< begin<<endl; // Outputs the second begin, after the program has
// gone through and output
}
int main()
{
printnum(1);
return 0;
}
OP:
1
2
3
4
5
6
7
8
9
9
8
7
6
5
4
3
2
1
在上面的代码中,我理解直到第9个输出。但是,为什么在if循环之后的cout语句导致begin变量开始向后计数,直到它达到首次调用printvalue时的原始值为止? 我想我不太了解这里的退出条件。
不知道我缺少什么,任何帮助将不胜感激。
谢谢。
每个begin
都是唯一的,并且属于“当前”活动功能-其值永远不变。
递归函数的工作原理与其他函数完全相同; 命名另一个参数与一个无关紧要。
如果您有这些:
void f(int x);
void g(int x)
{
cout << x << endl;
f(x+1);
cout << x << endl;
}
(我希望)如果g
打印两个不同的数字,您会感到非常惊讶。
递归的工作原理与以下示例(更小)完全一样,该示例使用唯一函数而不是带参数的递归:
void printnum_3()
{
cout << 3 << endl;
cout << 3 << endl;
}
void printnum_2()
{
cout << 2 << endl;
printnum_3();
cout << 2 << endl;
}
void printnum_1()
{
cout << 1 << endl;
printnum_2();
cout << 1 << endl;
}
int main()
{
printnum_1();
}
因此,让我们看看调用printnum(1)
时会发生什么。 begin
等于1
,它使用cout
打印,然后printnum(2)
。 但是,当程序离开printnum(2)
函数时会发生什么? 它继续执行printnum(1)
从地方,在那里printnum(2)
被调用。 因此,要执行的下一行是cout << begin
。 begin
仍然等于1
,因为我们正在执行printnum(1)
函数。 这就是为什么在末尾再次打印1
原因。 其他函数调用的情况完全相同。 例如,当printnum(9)
,它打印9
,然后if
检查失败(开始不少于9
),然后再次打印9
。
为什么if循环之后的cout语句导致begin变量开始倒计数,直到它达到首次调用printvalue时的原始值?
首先, 没有循环 。 有您需要了解的调用堆栈。 当(begin < 9)
变为false
即begin = 9
时,递归调用停止。 您会看到调用栈正在逐渐消失。
函数中的第一个cout
打印顺序[1..9]
,第二个cout
打印减小顺序[9..1]
。
您的代码执行如下:
cout<< 1 <<endl; //enter1
cout<< 2 <<endl; //enter2
cout<< 3 <<endl; //enter3
...
cout<< 8 <<endl; //enter8
cout<< 9 <<endl; //enter9
cout<< 9 <<endl; //exit9
cout<< 8 <<endl; //exit8
...
cout<< 3 <<endl; //exit3
cout<< 2 <<endl; //exit2
cout<< 1 <<endl; //exit1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.