我正在尝试从一本书中学习 C,但有些东西对我来说解释得不够清楚。
以下代码
1) 使用递归函数将啤酒瓶从 99 倒数到 0。2)一旦瓶子用完,它会打印“墙上没有瓶子了”,然后 3)将瓶子一一放入回收站
... #more of same above
3 bottles of beer on wall, 3 bottles of beer
Take one down, pass around, 2 bottls of beer
2 bottles of beer on wall, 2 bottles of beer
Take one down, pass around, 1 bottls of beer
1 bottles of beer on wall, 1 bottles of beer
Take one down, pass around, 0 bottls of beer
There are no more bottles on the wall.
Put bottle in recycling, 1 empty bottles in bin
Put bottle in recycling, 2 empty bottles in bin
Put bottle in recycling, 3 empty bottles in bin
.... #pattern continues
我理解它是如何倒计时的,以及为什么它说不再有啤酒瓶,但我不明白将瓶子放入回收利用的代码(printf)是如何被调用的,因为它在条件的 else 部分,并且,一旦瓶子的数量达到 0,该函数就永远不会返回到条件的 else 部分。
问题,最终的 printf (“将瓶子放入回收中......”)如何被调用 99 次,它如何能够逐个增加瓶子?
代码
void singTheSong(int numberOfBottles)
{
if(numberOfBottles == 0){
printf("There are no more bottles on the wall.\n");
}else {
printf("%d bottles of beer on wall, %d bottles of beer \n", numberOfBottles,numberOfBottles);
int oneFewer = numberOfBottles - 1;
printf("Take one down, pass around, %d bottls of beer \n", oneFewer);
singTheSong(oneFewer);
printf("Put bottle in recycling, %d empty bottles in bin \n", numberOfBottles);
}
}
int main(int argc, const char * argv[])
{
singTheSong(99);
return 0;
}