• 输出斐波那契数列前20项,每输出5个数换行


    斐波那契数列:1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...  这个数列从第3项开始,每一项都等于前两项之和。
     
    方法一(变量):
    public class FibonacciTset {
        public static void main(String[] args) {
            int a = 1, b = 1, c = 0;
            System.out.println("斐波那契数列前20项为:");
            System.out.print(a + "	" + b + "	");
            //因为前面还有两个1、1 所以i<=18
            for (int i = 1; i <= 18; i++) {
                c = a + b;
                a = b;
                b = c;
                System.out.print(c + "	");
                if ((i + 2) % 5 == 0)
                    System.out.println();
            }
                
        }
    
    }

    方法二(数组):

    public class FibonacciTset {
        public static void main(String[] args) {
            int arr[] = new int[20];  
            arr[0] = arr[1] = 1;  
            System.out.println("斐波那契数列前20项为:");
            System.out.print(arr[0] + "	" + arr[1] + "	");
            for (int i = 2; i < arr.length; i++) {  
                arr[i] = arr[i - 1] + arr[i - 2];  
                System.out.print(arr[i] + "	");
                if ((i + 1) % 5 == 0)
                    System.out.println();
            }  
    }
    }

    方法三(递归):

    public class FibonacciTset {
         // 使用递归方法  
        private static int getFibo(int i) {  
            if (i == 1 || i == 2)  
                return 1;  
            else  
                return getFibo(i - 1) + getFibo(i - 2);  
        }  
    
        public static void main(String[] args) {    
            System.out.println("斐波那契数列的前20项为:");  
            for (int j = 1; j <= 20; j++) {  
                System.out.print(getFibo(j) + "	");  
                if (j % 5 == 0)  
                    System.out.println();  
            }       
                
        }
    }
    追梦的脚步,永不停息
  • 相关阅读:
    anything vs everything
    cong
    invalid initialization of non-const reference of type与discards qualifiers
    gvew
    3.2存储器层次结构 -- 《深入理解计算机系统》☆☆☆☆☆
    2.2优化编译器的能力和局限性
    2.1.2优化程序性能
    2.1.1优化程序性能
    linux中获取堆栈空间大小的方法
    优美的英文诗歌Beautiful English Poetry
  • 原文地址:https://www.cnblogs.com/liuzhenping/p/7527025.html
Copyright © 2020-2023  润新知