这是Thinking in java中的一道练习题:题目如下:
一个斐波那契数列有1,1,2,3,5,8,13,32,34等等组成,其中每一个数字都是前两个的和。创建一个方法,接受一个整数参数,并显示从第一个元素开始总共由该参数指定的个数所构成的所有斐波那契数字。例如:如果运行java Fibonacci 5(Fibonacci是类名),那么输出就是1,1,2,3,5.本人是初学,向高手求助,我想了好久没做出来

解决方案 »

  1.   


    public class Fibonacci {


    public static void printFibonacci(int i){
    for (int j = 1; j < i + 1; j++) {
    System.out.printf("%d ",getFibonacci(j));
    }
    }

    public static int getFibonacci(int n) {
        return 
               (int) ((Math.pow(((1.0 + Math.sqrt(5)) / 2.0), n) - Math.pow(((1.0 - Math.sqrt(5)) / 2.0), n)) 
                     / Math.sqrt(5));
    }
    }
      

  2.   

    a[0]=1
    a[1]=1
    a[n]=a[n-1]+a[n-2]
    所以:
    foo (n){
      if (n=1)
        return 1;
      else if (n=2)
        return 1;
      else if (n > 0)
        x = foo(n-1)+foo(n-2)
        return x
    }main (n){
      for(i=1 to n){
       print foo(i)
      }
    }    
      

  3.   

    这个公式是用 组合数学 中的 生成函数 推导出来的
    有兴趣可以自己 Google 下
      

  4.   

    下面给个用递推得到的
    相比与递归可以节约很多空间与运算public static void printFibonacci(int i) {
    if(i < 0){
    System.out.println("参数请输入输入正整数");
    return;
    }
    if(i < 3){
    for (int j = 0; j < i; j++) {
    System.out.printf("1 ");
    }
    System.out.println();
    return;
    }
    PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
    int head = 1;
    int end = 1;
    int temp = 2;
    out.print("1 1 ");
    while (temp < i) {
    head += end;
    head ^= end;
    end ^= head;
    head ^= end;
    out.printf("%d ", end);
    temp++;
    }
    out.println();
    out.flush();
    }
      

  5.   


    public class Test {
    public static void main(String[] args) {
    fibonacci(8);
    }

    public static void fibonacci(int index){
    for(int i=1;i<index+1;i++){
    System.out.print(f(i)+",");
    }
    }

    public static int f(int n){
    if(n == 1 || n == 2){
    return 1;
    }

    else{
    return f(n-1)+f(n-2);
    }
    }
    }
      

  6.   


    import java.util.Scanner;
    class Mainfei
    {
    public static void main(String args[])
    {
    Scanner scan=new Scanner(System.in);
    int num=scan.nextInt();
     for(int i=1;i<=num;i++)
     System.out.print(feibo(i)+"  ");
    }
    //定义函数
    public static int feibo(int n)
    {
    if(n==1)
    return 1;
    else
    if(n==2)
    return 1;
    else 
    return feibo(n-1)+feibo(n-2);
    }
    }
    楼主这是代码,希望对你有用
      

  7.   

    请无视我5 楼写的  太 2B 了
    再发下
    public static void printFibonacci(int i) {
    if(i < 0){
    System.out.println("参数请输入输入正整数");
    return;
    }
    PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
    int head = 0;
    int end = 1;
    int temp = 1;
    while (temp <= i) {
    head += end;
    head ^= end;
    end ^= head;
    head ^= end;
    out.printf("%d ", head);
    temp++;
    }
    out.println();
    out.flush();
    }
      

  8.   

    keeya0416 is Knuth of CSDN:)