首页 > 学院 > 开发设计 > 正文

Java解决题目:有一对兔子,从出生第三个月起每个月都生一对兔子,小兔子长到第三个月后,每个月又生一对兔子。。。

2019-11-14 15:29:45
字体:
来源:转载
供稿:网友

题目:有一对兔子,从出生第三个月起每个月都生一对兔子,小兔子长到第三个月后,每个月又生一对兔子,假如兔子都不死,问M个月时兔子的数量,M为键盘读入的正整数。(请用java语言作答)

样例输入:

3

样例输出:

第1个月的兔子对数:1
第2个月的兔子对数:1
第3个月的兔子对数:2

代码示例:

import java.util.Scanner;/** * @author ForeverLover */public class Rabbit {	public static void main(String[] args) {		long s1 = 1;		long s2 = 1;		int count;		long temp;		Scanner in = new Scanner(System.in);		count = in.nextInt();		for (int i = 1; i <= count; i++) {			if (i == 1) {				System.out.PRintln("第" + i + "个月的兔子对数:" + s1);				continue;			} else if (i == 2) {				System.out.println("第" + i + "个月的兔子对数:" + s2);				continue;			} else {				temp = s2;				s2 = s1 + s2;				s1 = temp;				System.out.println("第" + i + "个月的兔子对数:" + s2);			}		}	}}

这涉及到的是斐波那契数列,公式:S(n)=S(n-1)+S(n-2)

  所谓斐波那切数列,又称黄金分割数列,是指这样的一个数列0、1、1、2、3、5、8、13、21、34、&hellip;…(当然我们这里是从1开始),具体详细介绍请点我


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表