母牛小牛问题的算法
母牛生小牛Problem
设有一头小母牛,从出生第四年起每年生一头小母牛,按此规律,第N年时有几头母牛?
Input
本题有多组数据。每组数据只有一个整数N,独占一行。(1≤N≤50)
Output
对每组数据,输出一个整数(独占一行)表示第N年时母牛的数量
Sample Input
1
4
5
20
Sample Output
1
2
3
872 #include<iostream>
int cows(int year)
{int one=0,two=0,three=0,four=1;
if(year<4)
return 1;
else
for(int i=4;i<year+1;i++)
{ four=three+four;
three=two;
two=one;
one=four;
}
return one+two+three+four;
}
int main()
{using namespace std;
int n;
cout<<"输入年份:";
cin>>n;
while(cin)
{cout<<n<<"年后有"<<cows(n)<<"头母牛.(输入Q退出程序.)"<<endl;
cout<<"输入年份:";
cin>>n;}
return 0;
}
这题用递推的...
#include<iostream>
using namespace std;
int main()
{
int n;
int k;
int i;
k=1;
k=2;
k=3;
k=4;
for(i=5;i<60;i++)
k=k+k;
while(cin>>n && n)
{
cout<<k<<endl;
}
return 0;
} 补充一下,每一年的牛的数量等于去年所有牛的数量+新生牛的数量,而新生牛的数量,就是3年前的所有牛的个数,因为三年前有一批小牛刚刚出生,那些牛在现在这年已经可以生了... 斐波拉切数列变形 没有小公牛吗?那小母牛咋生的? 路过学习学习
页:
[1]