兔程序這是我的任務:C++爲死
一對剛出生的兔子(一名男,一個母)的被放在一個領域。兔子可以在一個月的時候交配,以便在第二個月結束時每對產生兩對新兔子然後死亡。
注:在第0個月,有0對兔子。在第一個月,有一對兔子。
- 寫一個程序 - 使用while循環 - 這需要幾個月的數量從用戶和 打印對兔子的數量在這個月底。
- 在同一個cpp文件中,編寫一個遞歸函數rabbits(),將月份數作爲 輸入並返回該月末兔子對的數量。
- 在主程序中,使用用戶輸入的號碼調用函數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
}
}
重新格式化爲代碼,但是你可以砍下過度線間的空格,請? –
對於崩潰,您應該在調試器中運行您的程序。它會告訴你崩潰的位置,向你展示函數調用堆棧,並讓你檢查變量。所有這些都可以幫助你找出事故發生的地點和原因。 –
爲了給你一個關於崩潰原因的提示,它是由於無限遞歸導致的堆棧溢出。 –