我正在阅读一本书,其中有一章涉及 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;
}
输出读起来就像歌曲的演唱方式。我无法理解的是,numberOfBottles
变量如何更改其值?我看到它在 oneFewer
变量中被减一,但我不明白这是如何工作的。在我看来,日志上写着“墙上有 99 瓶熊,99 瓶啤酒。取下一个,传来传去,墙上有 98 瓶啤酒。”重复,从未低于 98。我不确定 numberOfBottles
值是如何改变的,因此 oneFewer
如何跟踪瓶子的数量。还有一个问题,我对这个话题的困惑是否是继续编程的坏兆头?直到此时我才确定下来。
最佳答案
关键在这里:
int oneFewer = numberOfBottles - 1;
singTheSong(oneFewer);
生成对 singTheSong
的新调用,其中 numberOfBottles
是 98 而不是 99。该函数获取 numberOfBottles
的本地副本,其中值为 98。
Stack numberOfBottles
------------------------------------------------------
singTheSong 99
singTheSong 98
singTheSong 97
singTheSong 96
... ...
singTheSong 1
singTheSong 0
当 numberOfBottles
归零时,堆栈中有 100 个对 singTheSong
的嵌套调用。最后,该函数不进行递归就返回,堆栈中等待的所有副本将一次返回一个。
关于c - C混淆中的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16641138/