具有递归和While循环的指数兔子

Exponentiating Rabbits with Recursion and While Loop

本文关键字:指数 循环 While 递归      更新时间:2023-10-16

几天前,我在这里问了一个关于Rabbits程序的问题,我几乎完成了它。问题是,当我输入0时,它崩溃了,无法运行。有人能帮我吗?这是我的任务:

一对刚出生的兔子(一只雄性,一只雌性)被放在田里。兔子能够在一个月大时交配,因此在第二个月底,每对兔子产下两对新兔子,然后死亡。注:在0月份,有0对兔子。在第一个月,有一对兔子。

  1. 使用while循环编写一个程序,从用户那里获取月数,并在月底打印兔子对的数量
  2. 在同一个cpp文件中,编写一个递归函数rabits(),该函数以月数为输入,并返回该月底兔子对的数量
  3. 在主程序中,使用用户输入的数字调用函数rabits()。输出这两个计算(即您通过循环获得的计算和递归函数返回的计算),看看它们是否相等

#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. nn";
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 << "nn";
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));
}
}

您的问题在这里:

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应该得到什么答案,从那里修复应该相当容易。

当您输入0时,您将创建一个负数(在条件if (month_function % 2 == 0)month_function == 0true)。当递归调用rabbits()时,您会创建一个相当深的递归,它最终会超过堆栈并导致程序崩溃。可能,您不希望为非正值输入递归。

如果输入0,则以下表达式的计算结果为true

if (month_function % 2 == 0) 

所以month_function被递减到-1。

由于-1,递归函数rabbits永远不会达到结束条件,并导致堆栈溢出。