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.
}
4 回答
7
这叫做溢出。
当算术运算试图创建一个太大而无法在可用存储空间内表示的数值时,就会发生整数溢出。[维基百科-整数溢出]
ints 可以表示最大值(2^32)-1。您的乘法得出的结果高于该值,因此会产生溢出。
multi将类型更改为long,您将不会遇到此问题(但仅适用于特定情况:如果您超过 a 可表示的最大值long,您将再次遇到该问题)
如前所述,将类型更改为long只会推迟问题,您可以使用 a 来解决它BigInteger,它可以处理任意精度的整数。
但只有在你真的需要时才使用它。如果您知道您的应用程序将在不超过long最大可表示值的情况下进行计算,则使用 a long,因为BigInteger它不是原始的,并且会比 a 慢得多long。
于 2013-11-11T17:45:01.730 回答
0
首先声明multi为long. 当一个值超过 Integer.MAX_VALUE 时,我“溢出”并变为负数。最大整数值刚刚超过 20 亿,所以它很快就会发生。
于 2013-11-11T17:46:05.363 回答
0
你遇到一个负值,那是因为多值超过了 Integer (2^31 -1) 的最大值。
您需要进行如下更改:
从
int multi= 1;
至
long multi= 1;
于 2013-11-11T17:46:25.387 回答
0
尝试这个
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};
long 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.
}
于 2013-11-11T17:48:31.477 回答