【发布时间】:2013-12-21 01:58:08
【问题描述】:
我正在自己练习 C 中的递归,我在网上找到了这个示例。 但是有一点我不明白。
void singSongFor(int numberOfBottles)
{
if (numberOfBottles == 0) {
printf("There are simply no more bottles of beer on the wall.\n\n");
}
else {
printf("%d bottles of beer 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\n",
oneFewer);
singSongFor(oneFewer); // This function calls itself!
// Print a message just before the function ends
printf("Put a bottle in the recycling, %d empty bottles in the bin.\n",
numberOfBottles);
}
}
然后我使用这样的主要方法:
int main(int argc, const char * argv[])
{
singSongFor(4);
return 0;
}
输出是这样的:
墙上有 4 瓶啤酒。 4瓶啤酒。 拿下一个,传过来,墙上有 3 瓶啤酒。
墙上有 3 瓶啤酒。 3瓶啤酒。 拿下一个,传过来,墙上有 2 瓶啤酒。
墙上有 2 瓶啤酒。 2瓶啤酒。 拿下一个,传过来,墙上有 1 瓶啤酒。
墙上有 1 瓶啤酒。 1瓶啤酒。 拿下一个,传过来,墙上0瓶啤酒。
墙上再也没有啤酒瓶了。
将一个瓶子放入回收站,1 个空瓶子放入垃圾箱。
将一个瓶子放入回收箱,2个空瓶子放入垃圾箱。
将一个瓶子放入回收箱,3个空瓶子放入垃圾箱。
将一瓶放入回收箱,4个空瓶放入垃圾箱。
我非常了解第一部分,直到我谈到“墙上根本没有啤酒瓶了。我不明白瓶子的可变数量是如何从 1 增加到 4 的。
【问题讨论】:
标签: c recursion procedural