不会死的斐波那契兔
Fibonacci Rabbits that don't die
一对刚出生的兔子(一只雄性,一只雌性)被放在田里。兔子能够在一个月大时交配,因此在第二个月底,每对兔子产下两对新兔子,然后死亡。
注:在0月份,有0对兔子。在第一个月,有一对兔子。
-
使用while循环编写一个程序,从用户那里获取月数,并在月底打印兔子对的数量。
-
在同一个cpp文件中,编写一个递归函数rabits(),该函数以月数为输入,并返回该月底兔子对的数量。
-
在主程序中,使用用户输入的数字调用函数rabits()。输出这两个计算(即您通过循环获得的计算和递归函数返回的计算),看看它们是否相等。
该描述相当不言自明。我已经有了主程序(常规的斐波那契函数),但我不知道如何实现兔子繁殖后死亡。我已经知道每隔一个月兔子的数量就会翻倍,但我不知道如何实施。提前感谢。
#include <iostream>
using namespace std;
int rabbits (int);
int main ()
{
int x, month, result, counter = 0, rab_now, rab_lastmonth = 1, rab_twomonthsago = 0;
cout << "Please enter the month nn";
cin >> month;
cout << "n";
result = rabbits (month);
while (counter <= month - 1)
{
rab_now = rab_lastmonth + rab_twomonthsago;
x = rab_lastmonth;
rab_lastmonth = rab_now;
rab_twomonthsago = x;
counter++;
}
cout << "At the end of month " << month << ", there will be " << rab_lastmonth << "
pairs of rabbits" << endl;
system("PAUSE");
return 0;
}
int rabbits (int month)
{
if (month == 0)
{
return 0;
}
else if (month == 1)
{
return 1;
}
else
{
return (rabbits (month + 1) + rabbits (month - 2));
}
}
您的函数几乎是正确的,只有一个小错误——可能是打字错误:
return (rabbits (month + 1) + rabbits (month - 2));
–你想要上个月的兔子,而不是下个月的。将+
更改为-
:
return (rabbits (month - 1) + rabbits (month - 2));
就这样。
顺便说一句,试着用一个更大的月数来调用该函数,比如20或30。你注意到演出的情况了吗?特别是与迭代实现相比?你能想出一种更有效地实现递归函数的方法吗?(脑筋急转弯:除非你已经知道如何实现,否则这不是微不足道的)。
相关文章:
- 没有找到相关文章