使用for循环打印第n个斐波那契数

时间:2018-11-15 18:24:38

标签: java fibonacci

我使用return编写了该程序,但希望该程序仅使用run方法和for循环来做完全相同的事情。它应该在斐波那契数列中打印第n个数字。

import acm.program.*;


public class TESTfibonacci extends ConsoleProgram {

    public void run() {

        long n = readInt("Enter a number: ");
        println(fibo(n));
    }

        // Prints the n-th Fibonacci number.
        long fibo(long n) {
        if (n == 0) {
            return 0;
        } else if (n <= 2) {
            return 1;
        } else {
            return fibo(n - 2) + fibo(n - 1);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以为此使用动态编程。该代码取自here

class Fibonacci {
  static int fib(int n) {
    /* Declare an array to store Fibonacci numbers. */
    int f[] = new int[n + 2]; // 1 extra to handle case, n = 0
    int i; 

    /* 0th and 1st number of the series are 0 and 1*/
    f[0] = 0;
    f[1] = 1;

    for (i = 2; i <= n; i++) {
    /* Add the previous 2 numbers in the series 
        and store it */
      f[i] = f[i - 1] + f[i - 2];
    }

    return f[n];
  }

  public static void main(String args[]) {
    int n = 9;
    System.out.println(fib(n));
  }
}