为什么乘积后我的乘积结果为0

试图得到乘法的结果 我正在尝试找出子阵列产品,但结果是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

        static void SubbArr(int arr[]) {
            BigDecimal product = new BigDecimal(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.multiply(BigDecimal.valueOf(arr[k]));
                    }
                    System.out.println();
                }
            }
            System.out.println("product is:" + product);
        }
    

  • xnobis
    xnobis 回复

    Your problem is Integer Overflow.

    The value of your product went beyond the maximum value an int can hold.

    Quick possible fix: You can covert it to long.

    If the problem still exists, BigInteger or BigDecimal will be your rescue.

  • xiste
    xiste 回复

    您的乘法结果溢出。乘法结果太大,无法存储int类型。但是,我不确定为什么它显示为0。也许是未定义的行为。您可能要为此使用Java BigInt类。