当我在数组中将数字相乘时,我得到一个负数.我该如何纠正?

use*_*102 1 java arrays product

public static void main(String[]args){
    int A[]={2,4,6,9,5,4,5,7,12,15,21,32,45,5,6,7,12};
    int multi= 1;
    for (int i=0; i<A.length; i++) {
        multi *= A[i];
    }
    System.out.println("The product of the numbers in the array is " + multi );
    //I keep getting a negative value but when I shorten the array
    //to a few numbers I don't have any problems.
}
Run Code Online (Sandbox Code Playgroud)

Bac*_*ash 7

这叫做溢出.

当算术运算尝试创建一个太大而无法在可用存储空间中表示的数值时,会发生整数溢出.[ 维基百科 - 整数溢出 ]

ints可以表示最大值(2^32)-1.乘法得到的结果高于该值,因此会产生溢出.

multi类型更改为long,您将不会遇到此问题(但仅针对该特定情况:如果超过a表示的最大值long,则会再次出现此问题)


如上所述,将类型更改为long只会推迟问题,您可以使用a来解决它BigInteger,它可以处理任意精度的整数.

只有你真的必须使用它.如果您知道您的应用程序将在不超出long最大可表示值的情况下进行计算,那么使用a long,因为BigInteger它不是原语,并且比a慢得多long.