c++ - 不死的斐波那契兔子

标签 c++

一对刚出生的兔子(一公一母)被放在田里。兔子在一个月大时可以交配,因此在第二个月的月底,每对兔子都会生出两对新兔子,然后死去。

注:在第0个月,有0对兔子。第 1 个月,有 1 对兔子。

  1. 编写一个程序 - 使用 while 循环 - 从用户那里获取月数并打印该月末兔子对的数量。

  2. 在同一个 cpp 文件中,编写一个递归函数 rabbits(),它将月数作为输入,并返回当月月底的兔子对数。

  3. 在主程序中,使用用户输入的数字调用函数 rabbits()。输出两种计算结果(即您通过循环获得的计算结果和递归函数返回的计算结果)并查看它们是否相等。


该描述相当不言自明。我已经有了主程序(常规斐波那契函数),但我不知道如何实现兔子在繁殖后死亡。我已经知道每隔一个月,兔子的数量就会翻一番,但我不知道如何实现。提前致谢。

#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 \n\n";
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。您注意到性能方​​面的任何事情了吗?特别是与迭代实现相比?你能想出一种更有效地实现递归函数的方法吗(脑筋急转弯:这不是微不足道的,除非你已经知道如何处理它)。

关于c++ - 不死的斐波那契兔子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13828831/

相关文章:

c++ - 如何在c中创建位图数据?

c++ - vc++ 中出现运行时错误,但 gcc 中没有

c++ - 基于插件的软件的UML项目示例。

c++ - 如何存储和调用可变参数函数和值 vector ?

c++ - (WMI) ExecMethod 输出参数 - 无论调用结果如何,ResultingSnapshot 都是 NULL,为什么?

c++ - 如何将字符串转换为由 C++ 中的字符组成的字符串数组?

c++ - 混合 const 和非常量传递引用的参数顺序

c++ - 我怎样才能在内存中恰好有 2 位?

c++ - 我应该在使用 STL 集时重载 == 运算符吗?

c++ - Linux 下 OpenGL 中的段错误