二维数组应用,while(1)循环

麻雀虽小,五脏俱全
二维数组运用,while循环运用都很经典。
在这里插入图片描述

#include 
using  namespace  std;
int main()
{
	const int MAX = 50;
	int cow[MAX] = { 1,1,1 }; //前三年的初值都为1,第四年头才会生
	int n, i; //n年内,每年的母牛数,i是循环计数变量
	cout << "请输入相应年数:";
	cin >> n;
	while (1)
	{
		if (n > 0 && n < MAX)
		{
			for (i = 3; i < n; i++)
				cow[i] = cow[i - 1] + cow[i - 3];
			for (i = 0; i < n; i++)
				cout << "第" << i + 1 << "年时有" << cow[i] << "头母牛" << endl;
			break;
		}
		else
		{
			cout << "输入的年数不满足要求1~" << MAX << ",请重新输入:";
			cin >> n;
		}
	}
	return 0;
}

你可能感兴趣的:(程序赏析)