跳到主要内容

兔子问题

image-20201118102346706

# 用small(i)表示第i个月的小兔子的数目,
# 用big(i)表示第i个月大兔子的数目
# 题目要求就是 ? = small(n) + big(n)
# 而 small(i) = big(i - 1)
# big(i) = small(i - 1) + big(i - 1)

12-%E5%85%94%E5%AD%90%E9%97%AE%E9%A2%98/image-20201118103009198.png

#include <iostream>
using namespace std;

int n = 7;

int main()
{
// 定义数组
int small[12], big[12];
// 设定初始值
small[0] = 1;
big[0] = 0;
// 递推
for(int i = 1; i < n; i++)
{
small[i] = big[i - 1];
big[i] = small[i - 1] + big[i - 1];
}
// 输出总数
cout << "第" << n << "个月的兔子总数是"
<< small[n - 1] + big[n - 1] << endl;
}

直接计算兔子总数

image-20201118104341509

image-20201118104406298

#include <iostream>
using namespace std;
int n = 23;
int main()
{
// 定义数组
int total[100];
// 设定初始值
total[0] = 1;
total[1] = 1;
// 递推
for(int i = 2; i < n; i++)
{
total[i] = total[i - 1] + total[i - 2];
}
// 输出总数
cout << "第" << n << "个月的兔子总数是"
<< total[n - 1] << endl;
}

不用数组递推

image-20201118105013415

#include <iostream>
using namespace std;
int n = 23;
int main()
{
// 设定初始值
int dang_yue;
int qian_yue = 1;
int shang_yue = 1;
// 递推
for(int i = 2; i < n; i++)
{
dang_yue = qian_yue + shang_yue;
qian_yue = shang_yue;
shang_yue = dang_yue;
}
// 输出总数
cout << "第" << n << "个月的兔子总数是"
<< dang_yue<< endl;
}