题目描述:
有一只兔子,从出生后第3个月起每个月都生一只兔子,
小兔子长到第三个月后每个月又生一只兔子,假如兔子都不死,问每个月的兔子总数为多少?
分析: 通过题意可以知道,兔子长到第三个月才会开始产兔子,同时不考虑兔子死亡的情况。当输入一个月份时,输出这个月份的所有兔子的总数量。
情况如下:
月份 一个月的幼兔 两个月的幼兔 三个月的大兔(可以产兔) 总数量
1 1 0 0 1
2 0 1 0 1
3 1 0 1 2
4 1 1 1 3
5 2 1 2 5
... ... ... ... ...
方法一:采用顺推的方法求解问题
#include<iostream>
using namespace std;
int rabbit(int n)
{
int total = 0;
int r[100] = { 1, 1 }; //前两个月为1只兔子
if (n == 1 || n == 2) //兔子总数也是1
total = 1;
else
{
if (n >= 3) //第三个月开始为前两个月的兔子数量之和
{
for (int i = 2; i < n; i++)
{
r[i] = r[i - 1] + r[i - 2];
total = r[i];
}
}
}
return total;
}
int main()
{
int m;
cout << "Please the month:" << endl;
cin >> m;
cout << "total rabbits is:" << rabbit(m);
return 0;
}
2,方法二:递归直接调用
#include<iostream>
using namespace std;
int rabbit(int n)
{
int total = 0;
if (n == 1 || n == 2)
total = 1;
else
{
if (n >= 3)
{
{
total = rabbit(n - 1) + rabbit(n - 2); //直接调用,调用本身
}
}
}
return total;
}
int main()
{
int m;
cout << "Please input the month:" << endl;
cin >> m;
cout << rabbit(m);
return 0;
}