将一对新生的兔子(一只雄性,一只雌性)放入田间。兔子能够在一个月的时候交配,这样在第二个月结束时,每对产生两对新的兔子,然后死亡。 注意:在第0个月,有0对兔子。在第1个月,有1对兔子。
#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));
}
}
答案 0 :(得分: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_function
等于-1
。
你(很有可能)你的逻辑中也有一个错误。如果为月份函数输入2
,则返回0,这是错误的。考虑输入2应该得到什么答案,从那里修复应该相当容易。
答案 1 :(得分:2)
当您输入0
时,您会创建一个负数(条件if (month_function % 2 == 0)
为true
month_function == 0
)。然后递归调用rabbits()
时,会创建一个相当深的递归,最终会超出堆栈并导致程序崩溃。可能,您不希望输入非正值的递归。
答案 2 :(得分:2)
如果输入0,则以下表达式的计算结果为true
if (month_function % 2 == 0)
因此month_function
递减为-1。
由于-1,您的递归函数rabbits
永远不会达到结束条件并导致堆栈溢出。