2

このRabbitsプログラムについて数日前にここで質問しました. 問題は、0 を入力するとクラッシュして実行されないことです。誰かが私を助けてくれませんか、これが私の仕事です:

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

  1. while ループを使用して、ユーザーから月数を取得し、その月の終わりにウサギのペアの数を出力するプログラムを作成します。
  2. 同じ cpp ファイルに、入力として月数を受け取り、その月の終わりにウサギのペアの数を返す再帰関数 rabbits() を記述します。
  3. メイン プログラムで、ユーザーが入力した番号を使用して関数 rabbits() を呼び出します。両方の計算 (つまり、ループで取得したものと再帰関数が返すもの) を出力し、それらが等しいかどうかを確認します。

#include <iostream>
using namespace std;

int rabbits (int);

int main ()

{
int month_function, month_while, result_rec, result_while, counter = 0, rab_now, rab_lastmonth = 0, rab_twomonthsago = 1;

cout << "Please enter the month. \n\n";
cin >> month_function;
month_while = month_function;
cout << "\n";

if (month_function % 2 == 0) // if month entered is even, the recursive function will use month - 1 because the total number of rabbits doubles every other month
{
    month_function--;
}

result_rec = rabbits (month_function);

while (counter < month_while)
{
    if (counter % 2 == 0)
    {
    rab_now = rab_lastmonth + rab_twomonthsago;
    rab_lastmonth = rab_now;
    rab_twomonthsago = rab_now;
    }
    counter++;
    result_while = rab_lastmonth;
}

cout << "According to the recursive function, there are " << result_rec << " pairs of rabbits at the end of month " << month_while << "\n\n";

cout << "According to the while loop, there are " << result_while << " pairs of rabbits at the end of month " << month_while << endl;

if (result_rec = result_while)
{
    cout << "\n";
    cout << "They are equal!" << endl;
}
else
{
    cout << "They are not equal!" << endl;
}

return 0;
}

int rabbits (int month_function)

{
    if (month_function == 0)
    {
        return 0;
    }
    else if (month_function == 1)
    {
        return 1;
    }
    else
    {
       return (rabbits (month_function - 2) + rabbits (month_function - 2));
    }
}
4

3 に答える 3

3

あなたの問題はここにあります:

if (month_function % 2 == 0) // if month entered is even, the recursive function will use   month - 1 because the total number of rabbits doubles every other month
{
    month_function--;
}

0 を入力すると、これは true と評価されるため、month_functionequals になり-1ます。

(おそらく) ロジックにもバグがあります。月関数を入力する2と、0 が返されますが、これは間違っています。2 の入力でどのような答えが得られるかを考えてみてください。そこから修正するのはかなり簡単です。

于 2012-12-13T05:49:25.910 に答える
2

入力0すると、負の数が作成されます(条件if (month_function % 2 == 0)truefor ですmonth_function == 0)。その後、再帰的に呼び出すrabbits()と、かなり深い再帰が作成され、最終的にスタックを超えてプログラムがクラッシュします。おそらく、正でない値の再帰を入力したくないでしょう。

于 2012-12-13T05:48:22.173 に答える
2

0 を入力すると、次の式は true と評価されます

if (month_function % 2 == 0) 

したがってmonth_function、-1 にデクリメントされます。

-1 のため、再帰関数rabbitsは終了条件に到達せず、スタック オーバーフローが発生します。

于 2012-12-13T05:48:56.003 に答える