java一只母牛 一年生头小牛_题目2.一个农场有头母牛,现在母牛才一岁,要到四岁才能生小牛,四岁之后,每年生一头小牛。...

题目2.一个农场有头母牛,现在母牛才一岁,要到四岁才能生小牛,四岁之后,每年生一头小牛。

假设每次生的都是母牛,并且也遵守4年才生育并生母牛的原则。且所生的牛都不会死

问20年之后共有多少头牛?用c语言解决

从现在开始,牛的数量组成数列a[n]:

1,1,1,2,3,4,5,7,10,14,19,26。。。(n=0,1,……20)

求a[20]

从a[4]开始有规律a[i]=a[i-1]+a[i-4]

则程序为

#include "stdio.h"

#include "conio.h"

void main()

{

int a[21];

a[0]=1;

printf("now:%d\n",a[0]);

a[1]=1;

printf("1 year after:%d\n",a[1]);

a[2]=1;

printf("2 years after:%d\n",a[2]);

a[3]=2;

printf("3 years after:%d\n",a[3]);

for(int i=4;i<=20;i++)

{

a[i]=a[i-1]+a[i-4];

printf("%d years after:%d\n",i,a[i]);

}

getch();

}

==============================================

结果

now:1

1 year after:1

2 years after:1

3 years after:2

4 years after:3

5 years after:4

6 years after:5

7 years after:7

8 years after:10

9 years after:14

10 years after:19

11 years after:26

12 years after:36

13 years after:50

14 years after:69

15 years after:95

16 years after:131

17 years after:181

18 years after:250

19 years after:345

20 years after:476

==============================================

import java.io.BufferedReader;

import java.io.InputStreamReader;

class ReadData

{

public static InputStreamReader inreader=new

InputStreamReader(System.in);

public static BufferedReader breader=new

BufferedReader(inreader);

public static int readInt()throws Exception

{

String str;

System.out.println("请输入年数:");

str=breader.readLine();

str=str.trim();

return

Integer.parseInt(str);

}

}

public class CountCow

{

public static void main(String[] args)throws

Exception

{

ReadData r = new

ReadData();

int n = r.readInt();

long i = CountCow.fib(n);

System.out.println(i);

}

public static long fib(int n)

{

long s = 1;

if(n==1||n==2||n==3)

{

s = 1;

}

else

{

s =

CountCow.fib(n-1) + CountCow.fib(n-3);

}

return s;

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值