好的,这是我在学习过程中编写的简单代码。
void SingTheSong (int NumOfBottles)
{
if (NumOfBottles == 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", NumOfBottles, NumOfBottles);
int Bottleless = NumOfBottles - 1;
printf("Take one down pass it around, %d bottles of beer on the wall. \n", Bottleless);
SingTheSong(Bottleless);
printf("Put a bottle in the recycling bin, there are now %d empty bottles in the bin.\n", NumOfBottles);
}
}
int main(int argc, const char * argv[])
{
SingTheSong(99);
return 0;
}
我唯一不明白的是为什么程序运行时 SingTheSong(Botteless) 函数从 1 开始,为什么在墙上有 0 瓶啤酒后它显示 printf() 语句。只是有点困惑,因为我认为花括号内的所有内容都在再次运行 else 语句之前在 else 语句中执行。为什么不是这样呢?
例子:
“墙上有99瓶啤酒,99瓶啤酒。拿一瓶下来,传过去,墙上有98瓶啤酒。”
将一个瓶子放入回收箱,现在箱内有 1 个空瓶子”
“墙上有98瓶啤酒,98瓶啤酒。拿一瓶下来,传过去,墙上有97瓶啤酒。”
将一个瓶子放入回收箱,现在箱内有 2 个空瓶子”
我知道他是初学者的东西,我是初学者。有人可以向我解释一下这一点,这样我就不再兜圈子了。谢谢!
想象一下你知道什么SingTheSong
方法打印为N
。现在交易两个分支if
分别声明。什么时候NumOfBottles
为零,打印“无瓶”消息,然后返回。什么时候NumOfBottles
不为零,我们做以下三件事:
- 打印瓶子数量
N
- 打印任何内容
SingTheSong
方法打印为N-1
- 打印回收信息
N
中间的线是递归的:它可以扩展到相同的三行,如下所示:
- 打印瓶子数量
N
- 打印瓶子数量
N-1
- 打印任何内容
SingTheSong
方法打印为N-2
- 打印回收信息
N-1
- 打印回收信息
N
你可以一次又一次地这样做,直到中间的线变成“啤酒用完”的信息。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)