sách gpt4 ai đã đi

Chương trình Dead Rabbit C++

In lại 作者:行者123 更新时间:2023-11-30 02:01:41 28 4
mua khóa gpt4 Nike

这是我的作业:

一对刚出生的兔子(一公一母)被放在田里。兔子在一个月大时可以交配,因此在第二个月的月底,每对兔子都会生出两对新兔子,然后死去。

注:在第0个月,有0对兔子。第 1 个月,有 1 对兔子。

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

这就是我到目前为止自己得到的。 (虽然我的程序在使用大于 3 的数字时崩溃了。本质上我想知道我是否在回答这个问题。

#include < iostream >

sử dụng không gian tên 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
phản++;
}

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 "<<><>

trả về 0;
}

int rabbits(int month)
{
if (month==0)
{
trả về 0;
}
else if (month==1)
{
return 1;
}
else if (month==2) // so as not to double 0 in the else below.
{
return 2;
}
khác
{
return rabbits((month-2)*2); //since the population doubles every second month
}
}

1 Câu trả lời

看起来第 4 个月的堆栈溢出了。该行

return rabbits((month-2)*2);

意味着调用 rabbits(4) 将导致对 rabbits(4) 的递归调用。每次调用都会消耗少量堆栈,并会一直持续到堆栈最终溢出。

你是想用

return 2 * rabbits(month-2);

这里呢?这与行尾的评论更加一致。

关于死兔子的C++程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13859527/

28 4 0
Bài viết được đề xuất: c++ - 嵌套类在继承类中的可见性
Bài viết được đề xuất: c++ - 重载 >> 读取分数
Bài viết được đề xuất: java - 如何使wsdl生成的java类可序列化
Bài viết được đề xuất: c++ - 如何禁用特定的 IBM XL C++ 编译器警告?
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com