c++代码解释(关于母牛问题)

来源:百度知道 编辑:UC知道 时间:2024/09/18 18:55:58
一个农场有头母牛,现在母牛才一岁,要到四岁才能生小牛,四岁之后,每年生一头小牛。假设每次生的都是母牛,并且也遵守4年才生育并生母牛的原则,并且无死亡,请问n年后共有多少头牛?

#include <iostream>

using namespace std;

int cow(int cows)
{
int one=1;
int two=1;
int three=1;
int four=1;
int i=0;
int sum=0;
for(i = 4; i < cows + 1; i++)
{
four = one + three;
one = two;
two = three;
three = four;
}
sum = four;
return sum;
}
int main()
{
int cows;
cout << "请输入年数: ";
cin >> cows;
cout << "共有 " << cow(cows) << " 头牛" << endl;
return 0;
}
这段代码是对的 但是我不知道cow方法运行过程(主要是for里面不理解)或者说这个方法是用了什么算法公式做的吗
大侠帮忙详细解释下好吗
最好加上注释 嘿嘿

好有趣的问题……
这是我自己写的,也许对你有些帮助^_^
请你运行一下,蛮好玩的^_^
#include<iostream>
using namespace std;

void cows(int n){
int one , two ,three ,four ;
one=1;two=three=four=0;

for(int i=1;i<=n;i++){
four=three+four;
three=two;
two=one;
one=four;
}
cout<<"~~~~~~~~~~~~~~~~~~生成报告~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<" "<<n<<"年以后共产生牛牛:"<<(one+two+three+four)<<"只\n";
cout<<" 其中有一岁的小牛:"<<one<<"只\n";
cout<<" 其中有两岁的小牛:"<<two<<"只\n";
cout<<" 其中有三岁的小牛:"<<three<<"只\n";
cout<<" 其中有牛牛究极体:"<<four