import java.util.*;
public class Prac9FibonacciNumbers {
public static void main(String[] args) {
int[] x = new int[100];
x[0] = 1;
x[1] = 1;
for (int a = 2; a < 100; a++) {
x[a] = x[a - 1] + x[a - 2];
}
for (int a = 0; a < 100; a++) {
if(a < 99){
System.out.print(x[a] + ",");
}
else{
System.out.print(x[a]);
}
}
}
}
该程序旨在创建斐波纳契数列表.但是,出于某种原因,它在我的输出中间给出了负数.
我可以用
Math.abs()
但我想知道它为什么给我负数.输出低于.请帮助我理解这个问题.
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368,75025,121393,196418,317811,514229,832040,1346269,2178309,3524578,5702887,9227465,14930352,24157817,39088169,63245986,102334155,165580141,267914296,433494437,701408733,1134903170,1836311903,-1323752223,512559680,-811192543,-298632863,-1109825406,-1408458269,1776683621,368225352,2144908973,-1781832971,363076002,-1418756969,-1055680967,1820529360,764848393,-1709589543,-944741150,1640636603,695895453,-1958435240,-1262539787,1073992269,-188547518,885444751,696897233,1582341984,-2015728079,-433386095,1845853122,1412467027,-1036647147,375819880,-660827267,-285007387,-945834654,-1230842041,2118290601,887448560,-1289228135,-401779575,-1691007710,-2092787285,511172301,-1581614984,-1070442683,1642909629,572466946,-2079590721,-1507123775,708252800,-798870975,-90618175,-889489150,-980107325
解决方法:
Fibonacci数字将大幅增长.在第46个数字处,您开始获得负数,例如-1323752223.这是因为数字已经变得如此之大以至于它溢出了int数据类型.
你可以使用long []数组,但这只会推迟问题.您将开始在第92个数字处获得负数,例如-6246583658587674878,因为它将溢出long数据类型.
使用double将不具有如此大的精度.您可以使用BigIntegers,它具有任意精度和大小.
BigInteger[] x = new BigInteger[100];
x[0] = BigInteger.ONE;
x[1] = BigInteger.ONE;
你需要使用add方法.
x[a] = x[a - 1].add(x[a - 2]);