Fibonacci兔子不死

时间:2012-12-11 21:29:32

标签: c++

将一对新生的兔子(一只雄性,一只雌性)放入田间。兔子能够在一个月的时候交配,这样在第二个月结束时,每对兔子会产生两对新的兔子然后死亡。

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

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

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

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


  4. 描述相当自我解释。我已经有了主程序(普通斐波那契函数),但我无法弄清楚如何实现兔子在繁殖后死亡。我已经知道,每隔一个月,兔子的数量增加一倍,但我不知道如何实施它。提前致谢。

    #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));
    }
    }
    

1 个答案:

答案 0 :(得分:4)

你的功能几乎是正确的,只有一个微不足道的错误 - 可能是一个错字:

return (rabbits (month + 1) + rabbits (month - 2));

- 你想要兔子来自之前的月,而不是下个月。将+更改为-

return (rabbits (month - 1) + rabbits (month - 2));

然后你去了。

顺便提一下,尝试使用较大的月份号码调用该功能 - 例如20或30.您是否注意到有关性能的任何信息?特别是与迭代实现相比?你能想出一种更有效地实现递归函数的方法吗(脑筋急转弯:除非你已经知道如何处理这个问题,否则这不是微不足道的。)