具有递归和While循环的指数兔子
Exponentiating Rabbits with Recursion and While Loop
几天前,我在这里问了一个关于Rabbits程序的问题,我几乎完成了它。问题是,当我输入0时,它崩溃了,无法运行。有人能帮我吗?这是我的任务:
一对刚出生的兔子(一只雄性,一只雌性)被放在田里。兔子能够在一个月大时交配,因此在第二个月底,每对兔子产下两对新兔子,然后死亡。注:在0月份,有0对兔子。在第一个月,有一对兔子。
- 使用while循环编写一个程序,从用户那里获取月数,并在月底打印兔子对的数量
- 在同一个cpp文件中,编写一个递归函数rabits(),该函数以月数为输入,并返回该月底兔子对的数量
- 在主程序中,使用用户输入的数字调用函数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 == 0
的true
)。当递归调用rabbits()
时,您会创建一个相当深的递归,它最终会超过堆栈并导致程序崩溃。可能,您不希望为非正值输入递归。
如果输入0,则以下表达式的计算结果为true
if (month_function % 2 == 0)
所以month_function
被递减到-1。
由于-1,递归函数rabbits
永远不会达到结束条件,并导致堆栈溢出。
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 在某些循环内使用vector.push_back时出现分段错误
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 为什么我的for循环不能正确获取argv
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- while循环中while循环的时间复杂度是多少
- 在矩阵逆变器上工作,由于某种原因,我的指数循环不起作用
- 具有递归和While循环的指数兔子
- 嵌套循环的指数加权平均 C++
- for循环错误地输出指数
- 使用循环C++中的指数
- 用set base/exponent为指数嵌套for循环
- 对于指数,特征表达式模板比手动循环慢