c - 理解啤酒瓶示例中的递归

标签 c recursion procedural

我自己在用 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/

相关文章:

c - if 语句中只有变量名意味着什么

c - C 数组中的垃圾值

c - 在 Idris 中使用 C 函数

c - K&R 4.2 书中的 atof()

c++ - SFML 中的程序纹理

PHP 测试,用于程序代码

python - 使用Python与类的子集总和

java - ruby 与 Java : Why world is going to end faster with Java?

java - 使用递归选择数组的奇数/偶数元素

c++ - 为什么我的 perlin 噪音这么..嘈杂?