统计每个月兔子的总数/华为机试(C/C++)(斐波拉契数列)

版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/thecentry。 https://blog.csdn.net/thecentry/article/details/82560021

题目描述

有一只兔子,从出生后第3个月起每个月都生一只兔子,小兔子长到第三个月后每个月又生一只兔子,假如兔子都不死,问每个月的兔子总数为多少?

    /**
     * 统计出兔子总数。
     * 
     * @param monthCount 第几个月
     * @return 兔子总数
     */
    public static int getTotalCount(int monthCount)
    {
        return 0;
    }

输入描述:

输入int型表示month

输出描述:

输出兔子总数int型

示例1

输入

9

输出

34

代码1:

//第三十七题 统计每个月兔子的总数
#include<iostream>
using namespace std;
int TatalNum(int iMonth)
{
	int total = 0;
	if (iMonth >= 3)
		total += TatalNum(iMonth - 1) + TatalNum(iMonth - 2);
	else if (iMonth == 1)
		return 1;
	else if (iMonth == 2)
		return 1;
	return total;
}
int main()
{
	int iMonth;
	while (cin >> iMonth)
	{
		cout << TatalNum(iMonth) << endl;
	}
	return 0;
}

代码2:不是本人写的

#include <iostream>
using namespace std;
int main()
{
	int month;
	while (cin >> month)
	{
		int first = 1;
		int second = 1;
		int result;
		for (int i = 3; i <= month; ++i)
		{
			result = first + second;//xn=xn-1 + xn-2
			first = second;
			second = result;
		}
		cout << result << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/thecentry/article/details/82560021