# 关于一个递归代码的问题～

``````void singTheSong(int numberOfBottles)
{
if (numberOfBottles == 0) {
printf("there are simply no more bottles of beer on the wall.\n");
} else {
printf("%d bottles of beer on the wall. %d bottles of beer.\n",
numberOfBottles, numberOfBottles);
int oneFewer = numberOfBottles - 1;
printf("Take one dowm, pass it around, %d bottles of beer on the wall.\n",
oneFewer);

singTheSong(oneFewer);
printf("put a bottle in the recycling, %d empty bottles in the bin.\n",
numberOfBottles);
}
}

int main(int argc, const char * argv[])
{
singTheSong(99);
return 0;
}

``````

99 bottles of beer on the wall. 99 bottles of beer.
Take one dowm, pass it around, 98 bottles of beer on the wall.
98 bottles of beer on the wall. 98 bottles of beer.
Take one dowm, pass it around, 97 bottles of beer on the wall.
97 bottles of beer on the wall. 97 bottles of beer.
Take one dowm, pass it around, 96 bottles of beer on the wall.
96 bottles of beer on the wall. 96 bottles of beer.
Take one dowm, pass it around, 95 bottles of beer on the wall.
......(中间重复的省略)
1 bottles of beer on the wall. 1 bottles of beer.
Take one dowm, 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, 98 empty bottles in the bin.
put a bottle in the recycling, 99 empty bottles in the bin.
Program ended with exit code: 0

``````printf("put a bottle in the recyling, %d empty bottles in the bin.\n",
numberOfBottles);
``````

2 个回答

`入参为3, 下面两行打印`
3 bottles of beer on the wall. 3 bottles of beer.
Take one dowm, pass it around, 2 bottles of beer on the wall.

`第一次递归调用singTheSong(2), 入参为2.`
`注意, 此时singTheSong(oneFewer); 之后的printf打印不会出现, 因为递归调用还没有返回;`
`后面你看到的 numberOfBottles一直在+1 现象的直接原因就在这.`
2 bottles of beer on the wall. 2 bottles of beer.
Take one dowm, pass it around, 1 bottles of beer on the wall.

`第二次递归调用singTheSong(1), 入参为1`
`同样, singTheSong(oneFewer) 之后的printf打印不会出现;`
1 bottles of beer on the wall. 1 bottles of beer.
Take one dowm, pass it around, 0 bottles of beer on the wall.

`第三次递归调用singTheSong(0), 入参为0, 直接打印下面一行, 并退出;`
`注意, 这里的退出是退回到第二次递归的栈. 并从singTheSong(oneFewer)之后的printf开始执行.`
there are simply no more bottles of beer on the wall.

`因为第二次递归入参为1, 所以这里打印下面一行`
`第二次递归调用退回到 第一次 递归的栈继续执行`
put a bottle in the recycling, 1 empty bottles in the bin.

`因为第一次递归入参为2, 所以这里打印下面一行`
`第一次递归调用退回到最初的singTheSong(3)继续执行`
put a bottle in the recycling, 2 empty bottles in the bin.

`最初的singTheSong(3)调用入参为3, 所以打印下面一行.`
put a bottle in the recycling, 3 empty bottles in the bin.

`singTheSong(99);`执行时需要调用`singTheSong(98);`但此时`singTheSong(99);`并没有执行完

``````printf("put a bottle in the recyling, %d empty bottles in the bin.\n",
numberOfBottles);
``````

###### 你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进