Java中的Fibonacci算法

San*_*eat 3 java fibonacci

我正在尝试解决算法类的作业问题,并且我一直在为下面编写的代码获取一个越界索引数组.我一直在尝试用Python来解决它,因为我对此非常满意,但我似乎得到了类似的异常.任何人都可以给我一个关于我在哪里出错的提示吗?

public class Fibonacci1 {
    public static long F(int N) {
        long a[]  = new long [100];
        a[0] = 0; /*sets up first 2 digits in the sequence*/
        a[1] = 1;
        if (N<2) {   
            return N;
        }
        a[N] = a[N-1] + a[N-2]; /*appends F num for next number in the list*/
        N++; 
        return a[N]; /*should return the last number*/
    }
    public static void main(String[] args) {
        for (int N = 0; N<100; N++)
            StdOut.println(N+" " + F(N));
    }
}
Run Code Online (Sandbox Code Playgroud)

gef*_*fei 10

何时N == 99,你N++在方法F中执行,然后调用return a[N],这意味着返回a[100]

  • 为了更清楚:一个可容纳100个元素的数组的索引为0到99,因此索引100超出范围. (3认同)

Man*_*nes 5

代码需要改变一下.您没有打印出正确的序列,因为该数组是一个局部变量,应该是一个静态变量.还应该删除n ++.下面的代码并不漂亮,但它的工作原理.

public class Fibonacci1 {
    static long a[] = new long[100];

    public static long F(int N) {
        a[0] = 0; /* sets up first 2 digits in the sequence */
        a[1] = 1;
        if (N < 2) {
            return N;
        }
        a[N] = a[N - 1] + a[N - 2]; /* appends F num for next number in the list */
        return a[N]; /* should return the last number */
    }

    public static void main(String[] args) {
        for (int N = 0; N < 100; N++)
            System.out.println(N + " " + F(N));
        }
}
Run Code Online (Sandbox Code Playgroud)

  • 没问题.在盯着我们的代码之前,我们都去过那里.祝好运. (3认同)