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

前端 未结 9 1532
悲哀的现实
悲哀的现实 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:59

    Somewhere in the middle you get 0 as the product. So, your entire product will be 0.

    In your case :

    for (int i = 10; i < 99; i++) {
        if (product < Integer.MAX_VALUE)
            System.out.println(product);
        product *= i;
    }
    // System.out.println(product);
    
    System.out.println(-2147483648 * EvenValueOfi); // --> this is the culprit (Credits : Kocko's answer )
    
    O/P :
    1
    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  --> Multiplying this and the current value of `i` will also give -2147483648 (INT overflow)
    -2147483648  --> Multiplying this and the current value of `i` will also give -2147483648 (INT overflow)
    
    -2147483648  ->  Multiplying this and the current value of 'i' will give 0 (INT overflow)
    0
    0
    0
    

    Every time you multiply the current value of i with the number you get 0 as output.

提交回复
热议问题