简体   繁体   中英

why is 24 * 60 * 60 * 1000 * 1000 divided by 24 * 60 * 60 * 1000 not equal to 1000 in Java?

为什么在Java中24 * 60 * 60 * 1000 * 1000除以24 * 60 * 60 * 1000不等于1000?

Because the multiplication overflows 32 bit integers. In 64 bits it's okay:

public class Test
{
    public static void main(String[] args)
    {
        int intProduct = 24 * 60 * 60 * 1000 * 1000;
        long longProduct = 24L * 60 * 60 * 1000 * 1000;
        System.out.println(intProduct); // Prints 500654080
        System.out.println(longProduct); // Prints 86400000000
   }
}

Obviously after the multiplication has overflowed, the division isn't going to "undo" that overflow.

You need to start with 24L * 60 * ... because the int overflows.

Your question BTW is a copy/paste of Puzzle 3: Long Division from Java Puzzlers ;)

If you want to perform that calculation, then you must either re-order the operations (to avoid overflow) or use a larger datatype. The real problem is that arithmetic on fixed-size integers in Java is not associative; it's a pain, but there's the trade-off.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM