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();
}