Unexpected negative number in Java

import java.util.*;
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]);

                }

            }

        }

    }

This program is designed to create a Fibonacci number list But, for some reason, it gives a negative number in the middle of my output

I can use it

Math.abs()

But I wonder why it gives me negative numbers The output is below Please help me understand the problem

Solution

Fibonacci figures will increase significantly At the 46th number, you begin to get a negative number, such as - 1323752223 This is because the number has become so large that it overflows the int data type

You can use the long [] array, but this will only delay the problem You will begin to get a negative number at the 92nd number, such as - 62465836587674878, because it will overflow the long data type

Using double will not have such precision You can use BigIntegers, which have any precision and size

BigInteger[] x = new BigInteger[100];
x[0] = BigInteger.ONE;
x[1] = BigInteger.ONE;

You need to use the add method

x[a] = x[a - 1].add(x[a - 2]);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>