0
点赞
收藏
分享

微信扫一扫

JAVA实现输出Fibonacci数列

_鱼与渔_ 2022-04-03 阅读 47
java

有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第3个月后每个月又生一对兔子,如果兔子都不死,请输出1~N个月的兔子对数是多少?(Fibonacci数列 {1,1,2,3,5,8,13,21,34......} )

①用数组实现

public static void main(String[] args) {
    Scanner N = new Scanner(System.in);
    System.out.println("输入月份n:");
    int n = N.nextInt();
    int[] a = new int[n];
    a[0] = 1;
    if (n > 1) {
        a[1]=1;
        for (int i = 2; i < a.length; i++) {
            a[i] = a[i - 1] + a[i - 2];
        }
        for (int c : a) System.out.print(c + " ");
    }
    else for (int c : a) System.out.print(c + " ");
}

 

因为使用了a【i-2】,所以对月份进行了if的分组

②用递归调用实现。

public static void main(String[]args){
        Scanner Q=new Scanner(System.in);
        System.out.println("输入月份a");
        int a= Q.nextInt();
        for(int i=1;i<=a;i++){
        System.out.print(tuzi(i)+" ");}
    }
    public static int tuzi(int a){
        if(a<=2)
        {return 1;}
        return tuzi(a-1)+tuzi(a-2);
    }
}

 

刚学的缘故,有些代码应该是可以更简洁的,大家有更好的方法,可以指导我~

举报

相关推荐

0 条评论