Hen*_*y F 3 c variables recursion
我正在写一本书,其中包括一章处理C中的递归.它将99瓶歌曲打印到日志中.这是代码:
void singTheSong (int numberOfBottles) {
if (numberOfBottles == 0) {
printf("There are no more bottles left.\n");
} else {
printf("%d bottles of bear on the wall, %d bottles of beer.\n", numberOfBottles,
numberOfBottles);
int oneFewer = numberOfBottles - 1;
printf("Take one down, pass it around, %d bottles of beer on the wall.\n", oneFewer);
singTheSong(oneFewer);
}
}
int main(int argc, const char * argv[])
{
singTheSong(99);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出就像歌曲的歌唱一样.我理解的是,numberOfBottles变量如何改变它的价值?我看到它被oneFewer变量中的一个减去了,但是我无法理解它是如何工作的.在我看来,原木上写着"墙上挂着99瓶啤酒,99瓶啤酒.拿下一瓶啤酒,然后四处走动,墙上挂着98瓶啤酒." 反复地,没有浸没在98以下.我不确定numberOfBottles价值是如何变化的,因此如何oneFewer跟踪瓶子的数量.还有一个问题,我对这个主题的困惑是继续编程的一个坏兆头吗?我把它钉在了这一点上.
关键在这里:
int oneFewer = numberOfBottles - 1;
singTheSong(oneFewer);
Run Code Online (Sandbox Code Playgroud)
singTheSong生成一个新的调用,其中numberOfBottles98是99而不是99.该函数获取numberOfBottles值为98 的本地副本.
Stack numberOfBottles
------------------------------------------------------
singTheSong 99
singTheSong 98
singTheSong 97
singTheSong 96
... ...
singTheSong 1
singTheSong 0
Run Code Online (Sandbox Code Playgroud)
到达numberOfBottles零时,有100个嵌套调用singTheSong坐在堆栈上.最后,函数返回而不进行递归,并且正在等待的堆栈中的所有副本将一次返回一个.