Java实现斐波那契数列Fibonacci

import java.util.Scanner;
public class Fibonacci {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in=new Scanner(System.in);
        System.out.println("斐波那契数列的个数是:");
        int total=in.nextInt();
        System.out.println("斐波那契数列是:");
        for(int i=1;i<=total;i++){           
             System.out.print(fib(i)+"\t");
             if(i%10==0)
                 System.out.println();  
        }
    }
    public static long fib(int i) {
        // TODO Auto-generated method stub
        long f1=1;
        long f2=1;
        long f3=2;
        if(i==1)
            return 1;
        if(i==2)
            return 2;
        for(int j=3;j<=i;j++){
            f3=f1+f2;
            f1=f2;
            f2=f3;
        }
        return f3;
    }   
}

你可能感兴趣的:(java,fibonacci)