Why does Java think that the product of all numbers from 10 to 99 is 0?

前端 未结 9 1513
悲哀的现实
悲哀的现实 2020-12-02 05:56

The following block of codes gives the output as 0.

public class HelloWorld{

    public static void main(String []args){
        int product = 1;
        fo         


        
9条回答
  •  暖寄归人
    2020-12-02 06:55

    It looks like an integer overflow.

    Take a look at this

    BigDecimal product=new BigDecimal(1);
    for(int i=10;i<99;i++){
        product=product.multiply(new BigDecimal(i));
    }
    System.out.println(product);
    

    Output:

    25977982938941930515945176761070443325092850981258133993315252362474391176210383043658995147728530422794328291965962468114563072000000000000000000000
    

    Output no longer be a int value. Then you will get wrong value because of the overflow.

    If it overflows, it goes back to the minimum value and continues from there. If it underflows, it goes back to the maximum value and continues from there.

    More info

    Edit.

    Let's change your code as follows

    int product = 1;
    for (int i = 10; i < 99; i++) {
       product *= i;
       System.out.println(product);
    }
    

    Out put:

    10
    110
    1320
    17160
    240240
    3603600
    57657600
    980179200
    463356416
    213837312
    -18221056
    -382642176
    171806720
    -343412736
    348028928
    110788608
    -1414463488
    464191488
    112459776
    -1033633792
    -944242688
    793247744
    -385875968
    150994944
    838860800
    -704643072
    402653184
    2013265920
    -805306368
    -1342177280
    -2147483648
    -2147483648>>>binary representation is 11111111111111111111111111101011 10000000000000000000000000000000 
     0 >>> here binary representation will become 11111111111111111111111111101011 00000000000000000000000000000000 
     ----
     0
    

提交回复
热议问题