几天前我在这里问了一个关于这个兔子程序的问题,我几乎完成了它。问题是当我输入 0 时,它会崩溃并且无法运行。有人可以帮帮我吗,这是我的任务:
一对刚出生的兔子(一公一母)被放在一块田地里。兔子可以在一个月大的时候交配,所以在第二个月末,每对兔子都会生出两对新兔子,然后死去。注:第 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));
}
}