我的 Java 斐波那契数列中的错误


public class Arrays {
public static void main(String[] args){
long Fib[] = new long[100];
Fib[0] = 1;
Fib[1] = 1;
int i = 0;
    while(i <= 100){
        Fib[i+2]= Fib[i] + Fib[i+1];
        System.out.println(Fib[i]);
        i++;
    }
}
}

我用它来找到斐波那契数,但它在第 94 学期左右开始给我奇怪的读数。有人愿意解释吗?我对Java完全陌生,所以请不要讨厌它,如果它是显而易见的。以下是错误输出的一些片段,但其他一切看起来都很好:

832040
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
1346269

63245986
at Arrays.main(102334155
Arrays.java:8)
165580141

4660046610375530309
7540113804746346429
-6246583658587674878
1293530146158671551
-4953053512429003327
-3659523366270331776
-8612576878699335103
6174643828739884737

这是解决方案。 您正在尝试访问第 102 个元素 i + 2,其中 i = 100

 Fib[0] = 1;
 Fib[1] = 1;
 int i = 2;
 while(i < 100){
      Fib[i]= Fib[i-1] + Fib[i-2];
      System.out.println(Fib[i]);
      i++;
 }
此外,第 97 个斐波那契数超过了 long 之间的范围,介于 -9,223,372,036,854,775,808

和 9,223,372,036,854,775,807 之间。 第 97 位斐波那契是 83,621,143,489,848,410,000 您应该使用 BigInteger 而不是 long

下面的代码打印直到 1000 位斐波那契数。

   BigInteger first = new BigInteger("0");
    BigInteger second = new BigInteger("1");
    BigInteger temp;// = new BigInteger("0");
    int counter = 1;
     while(numberOfDigits(second) < 1000)
     {
         temp = new BigInteger(second.toString());
         second = second.add(first);
         first = new BigInteger(temp.toString());
         counter++;
     }
     System.out.print(counter);

}
public static int numberOfDigits(BigInteger number)
{
      return number.toString().length();
}
java.lang.ArrayIndexOutOfBoundsException: 100

表示数组索引 100 不存在。

`long Fib[] = new long[100];`

创建索引 0 - 99

i达到 98 时,Fib[i+2]的计算结果将变为 Fib[100] ,这将抛出ArrayIndexOutOfBoundsException,因为Fib的长度为 100 并且数组是零索引(如您通过分配 Fib[0] 所演示的那样(。

此外,您得到的是负面结果,因为结果太大而无法放入long,因此它们溢出。长整型的最大值是 9,223,372,036,854,775,807 ,第 93 个斐波那契数是第一个超过这个值的,值为 12,200,160,415,121,876,738

数组中不需要生成斐波那契数列。另一个技巧是使用双精度(长对于第 100 个斐波那契数来说太小了(

  double penultimate = 1; // <- long is not long enough ;) use double or BigInteger
  double ultimate = 1;
  System.out.println(penultimate);
  for (int i = 1; i < 100; ++i) {
    System.out.println(ultimate);
    double h = penultimate + ultimate;
    penultimate = ultimate;
    ultimate = h;
  }

此外,您可以迭代循环 98 次以获得序列。它将为您提供Fib[100] = 6174643828739884737的最后一个元素。

long Fib[] = new long[100];
Fib[0] = 1;
Fib[1] = 1;
int i = 0;
    while(i < 98){
                    Fib[i+2]= Fib[i] + Fib[i+1];
                    System.out.println(Fib[i]);
                    i++;
                }

最新更新