我正在阅读一本关于C语言递归的书籍,其中包括了一个章节,介绍如何用递归打印99瓶啤酒歌曲。以下是代码:
void singTheSong (int numberOfBottles) {
if (numberOfBottles == 0) {
printf("There are no more bottles left.\n");
} else {
printf("%d bottles of bear 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", oneFewer);
singTheSong(oneFewer);
}
}
int main(int argc, const char * argv[])
{
singTheSong(99);
return 0;
}
输出的内容和歌曲唱法一样。我不太明白的是,变量
numberOfBottles
是如何改变其值的?我看到它在oneFewer
变量中减去了一个,但我还是不理解这是如何工作的。在我的印象中,日志应该重复地读取“墙上有99瓶啤酒,99瓶啤酒。拿下一瓶,传递出去,墙上还有98瓶啤酒。”,而从未低于98。我不确定numberOfBottles
的值如何改变,因此也不知道oneFewer
如何跟踪瓶数。另外一个问题是,我对这个主题的困惑是否意味着我不能继续学习编程?在这一点上,我已经掌握了很多东西。