1

これが私の課題です:

生まれたばかりのうさぎ(オス一匹、メス一匹)を一組、畑に放します。ウサギは生後 1 か月で交尾できるため、2 か月の終わりに各つがいは 2 つの新しいつがいを生み出し、その後死亡します。

注: 月 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 に答える