我自己在用 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);
}
}
然后我使用一个 main 方法:
int main(int argc, const char * argv[])
{
singSongFor(4);
return 0;
}
输出是这样的:
4瓶啤酒在墙上。 4瓶啤酒。 取下一个,传来传去,墙上挂着3瓶啤酒。
墙上有3瓶啤酒。 3瓶啤酒。 取下一个,传来传去,墙上挂着2瓶啤酒。
墙上有两瓶啤酒。 2瓶啤酒。 取下一个,传来传去,1瓶啤酒在墙上。
1瓶啤酒在墙上。 1瓶啤酒。 取下一个,传来传去,0瓶啤酒在墙上。
墙上根本就没有啤酒瓶了。
将一个瓶子放入回收站,将 1 个空瓶子放入垃圾箱。
将一个瓶子放入回收站,将 2 个空瓶子放入垃圾箱。
将一个瓶子放入回收站,将 3 个空瓶子放入垃圾箱。
将一个瓶子放入回收站,将 4 个空瓶子放入垃圾箱。
我非常理解第一部分,直到我看到“墙上根本就没有更多的啤酒瓶了。之后我不明白瓶子的可变数量是如何从 1 增加到 4 的。
最佳答案
较小的啤酒瓶(及其相应的回收)处于内部功能中。您的函数树如下所示:
4 bottles of beer on the wall. 4 bottles of beer. Take one down, pass it around, 3 bottles of beer on the wall.
| 3 bottles of beer on the wall. 3 bottles of beer. Take one down, pass it around, 2 bottles of beer on the wall.
| | 2 bottles of beer on the wall. 2 bottles of beer. Take one down, pass it around, 1 bottles of beer on the wall.
| | | 1 bottles of beer on the wall. 1 bottles of beer. Take one down, pass it around, 0 bottles of beer on the wall.
| | | | There are simply no more bottles of beer on the wall.
| | | Put a bottle in the recycling, 1 empty bottles in the bin.
| | Put a bottle in the recycling, 2 empty bottles in the bin.
| Put a bottle in the recycling, 3 empty bottles in the bin.
Put a bottle in the recycling, 4 empty bottles in the bin.
关于c - 理解啤酒瓶示例中的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20714617/