1

这是我的任务:

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

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

  1. 编写一个程序 - 使用 while 循环 - 从用户那里获取月数,并在该月末打印兔子对的数量。
  2. 在同一个 cpp 文件中,编写一个递归函数 rabbits(),它将月数作为输入,并返回该月末的兔子对数。
  3. 在主程序中,使用用户输入的数字调用函数 rabbits()。输出这两个计算(即您使用循环获得的计算和递归函数返回的计算)并查看它们是否相等。

这就是我自己到目前为止所得到的。(我的程序在使用高于 3 的数字时崩溃。基本上我想知道我是否在回答这个问题。

#include < iostream >

using namespace std;

int rabbits(int month); //declaring function

//begin program

int main ()
{
    //defining variables
    int  month, counter = 0, rab_now = 0, rab_lastmonth = 1, rab_twomonthsago = 0;
    cout << "Please enter a month.";
    cin >> month;

    //start loop 
    while (counter <= month - 1)
    {
        rab_now = rab_lastmonth + (2*rab_twomonthsago); //doubles the birthrate of the rabbits
        rab_twomonthsago = rab_lastmonth;
        rab_lastmonth = rab_now -rab_lastmonth; //accounts for the death of parent rabbits
        counter++;
    }

    cout << "According to the while loop, there are " << rab_now << " pair(s) of rabbits at the end of month " << counter << endl;
    cout<< "According to the recursive function, there are "<< rabbits(month)<<" pair(s) of rabbits at the end of month "<<counter<<endl;

    return 0;
}

int rabbits(int month)
{
    if (month==0)
    {
        return 0;
    }
    else if (month==1)
    {
        return 1;
    }
    else if (month==2) // so as not to double 0 in the else below.
    {
        return 2;
    }
    else
    {
        return rabbits((month-2)*2); //since the population doubles every second month
    }
}
4

2 回答 2

4

看起来这溢出了第 4 个月的堆栈。该行

return rabbits((month-2)*2);

意味着调用rabbits(4)将导致对rabbits(4). 每次调用都会消耗少量的堆栈,并且会一直持续到堆栈最终溢出。

你的意思是使用

return 2 * rabbits(month-2);

而不是在这里?这与行尾的注释更一致。

于 2012-12-13T12:11:53.787 回答
0

你的意思是说

return fibonacci(n-1) + fibonacci(n-2);

于 2014-02-12T15:09:28.517 回答