试图得到乘法的结果 我正在尝试找出子阵列产品,但结果是0
public class SubArray {
public void SubbArr(int arr[]) {
int product = 1;
for(int i=0;i<arr.length;i++) {
for(int j=i;j<arr.length;j++) {
for(int k=i;k<=j;k++) {
System.out.print(arr[k]+" ");
product = product*arr[k];
}
System.out.println();
}
}
System.out.println("product is:"+product);
}
public static void main(String[] args) {
SubArray all = new SubArray();
int arr[] = {1,2,3,4,5,6};
all.SubbArr(arr);
// TODO Auto-generated method stub
}
}
因为您超出了int最大值,所以得到了0
If you want to get the result you can use
BigDecimal
Your problem is Integer Overflow.
The value of your
product
went beyond the maximum value anint
can hold.Quick possible fix: You can covert it to
long
.If the problem still exists,
BigInteger
orBigDecimal
will be your rescue.您的乘法结果溢出。乘法结果太大,无法存储int类型。但是,我不确定为什么它显示为0。也许是未定义的行为。您可能要为此使用Java BigInt类。