我自己正在练习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瓶啤酒。把一瓶拿下来,传过来,墙上放两瓶啤酒。
墙上有两瓶啤酒。2瓶啤酒。把一个拿下来,传过来,墙上放一瓶啤酒。
墙上有一瓶啤酒。一瓶啤酒。把一瓶拿下来,传过来,墙上有0瓶啤酒。
墙上根本没有啤酒瓶了。
在回收站里放一个瓶子,在垃圾箱里放一个空瓶子。
把一个瓶子放进回收站,两个空瓶子放进垃圾箱。
在回收站放一个瓶子,在垃圾箱里放三个空瓶子。
在回收站里放一个瓶子,在垃圾箱里放四个空瓶子。
我对第一部分的理解很好,直到我说到“墙上根本没有啤酒瓶了,后来我不明白瓶子的数量是如何从1增加到4的。
发布于 2013-12-21 02:00:53
请注意,最后一个printf使用了numberOfBottles变量,而且从未修改过。因此,在打印完oneFewer瓶后,它将使用numberOfBottles打印回收文本。请记住,每个函数的每个调用都有一个不同的局部变量化身。
如果缩进对函数的调用,可以更容易地看到:
4 bottles of beer on the wall...
3 bottles of beer on the wall...
2 bottles of beer on the wall...
1 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.现在,从同一列开始的每一行都是从函数的相同调用中写入的。你知道瓶子的数量和回收剂的数量吗?这是因为两者都使用相同的变量:numberOfBottles。
发布于 2013-12-21 02:03:32
小瓶啤酒(及其相应的回收利用)具有内在功能。函数树如下所示:
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.发布于 2013-12-21 02:04:26
逐步了解函数在调试器中所做的事情,您将看到这个递归是如何工作的。我不是学究,我真的想不出比这种互动方式更好的方法来说明这是在做什么。
https://stackoverflow.com/questions/20714617
复制相似问题