このRabbitsプログラムについて数日前にここで質問しました. 問題は、0 を入力するとクラッシュして実行されないことです。誰かが私を助けてくれませんか、これが私の仕事です:
生まれたばかりのうさぎ(オス一匹、メス一匹)を一組、畑に放します。ウサギは生後 1 か月で交尾できるため、2 か月の終わりには、各つがいから 2 つの新しいつがいが生まれ、その後死んでしまいます。注: 月 0 には、ウサギのペアが 0 組あります。1 か月目には 1 つがいのウサギがいます。
- while ループを使用して、ユーザーから月数を取得し、その月の終わりにウサギのペアの数を出力するプログラムを作成します。
- 同じ cpp ファイルに、入力として月数を受け取り、その月の終わりにウサギのペアの数を返す再帰関数 rabbits() を記述します。
- メイン プログラムで、ユーザーが入力した番号を使用して関数 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));
}
}