码迷,mamicode.com
首页 > 其他好文 > 详细

斐波拉契的兔子

时间:2019-11-12 01:21:28      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:str   for   方法   main   else   ret   兔子   static   ann   

package cn.gl.program25;

import java.util.Scanner;

/**
 * 题目:
 *     古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生对兔子,假如兔子不死,
 *  问每个月兔子总数为多少?
* @author 冷夜雨花未眠 E-mail:787831425@qq.com
* @version 创建时间:2019年11月11日
 */
public class Demo1 {
    public static void main(String[] args) {
        
        System.out.println("第1个月的兔子对数:1");
        System.out.println("第2个月的兔子对数:1");
        int f1 = 1, f2 = 1, f, M = 24;//设置最大月数为24
        for (int i = 3; i <= M; i++) {
            f = f2;
            f2 = f1 + f2;
            f1 = f;
            System.out.println("第" + i + "个月的兔子对数:" + f2);
        }
    }
}

这是第一种方法    

数列:1,1,2,3,5,8,13,21,34,55,89,144,233,·…它是一个线性递归数列

package cn.gl.program25;

import java.util.Scanner;

/**
 * 题目:
 *     古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生对兔子,假如兔子不死,
 *  问每个月兔子总数为多少?
* @author 冷夜雨花未眠 E-mail:787831425@qq.com
* @version 创建时间:2019年11月11日
 */
public class Demo1 {
    public static void main(String[] args) {
        
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        System.out.println("请输入查询第几个月的兔子对数:");
        System.out.println("总对数为:" + "\n" + f(n) + "对");

    }

    public static int f(int n) {
    
            if (n != 1 && n != 2) {
                return f(n - 1) + f(n - 2);
            } else
                return 1;
    
        
    }
}

这是第二种方法

斐波拉契的兔子

标签:str   for   方法   main   else   ret   兔子   static   ann   

原文地址:https://www.cnblogs.com/gl0102/p/11839125.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!