Java division returns incorrect result

后端 未结 5 1813
不思量自难忘°
不思量自难忘° 2021-01-15 15:28
 public static void main(String[] args) {
        final long a= 24 * 60 * 60 * 1000 * 1000;
        final long b= 24 * 60 * 60 * 1000;

        System.out.println(a/         


        
相关标签:
5条回答
  • 2021-01-15 16:03

    24 * 60 * 60 * 1000 * 1000 this cause numeric overflow since it will consider as an int value. So you will get odd result. You should use long here.

    You should use 24 * 60 * 60 * 1000 * 1000L (This is how you define long)

    How to initialize long in Java?

    0 讨论(0)
  • 2021-01-15 16:09

    24 * 60 * 60 * 1000 is 86400000. If you multiply it by 1000, it will overflow the int type (because the maximum value that an int can hold is 2147483647 which is a lot less than 86400000000) and you will get 500654080 for a.

    Then, when you divide the result by 86400000, you will get 5.

    In order to fix this, you need to explicitly specify that the result from the multiplication will be long - this is because all the numeric operators in Java produce integers, unless explicitly instructed to produce some other numeric type.

    Just appending a L on some of the operands will be sufficient:

    final long a = 24 * 60 * 60 * 1000 * 1000L;
    
    0 讨论(0)
  • 2021-01-15 16:13

    Agree with above answers You can achieve what you want in below two ways:

    public static void main(String[] args) {
            //way 1
            final long a =(long) 24 * 60 * 60 * 1000 * 1000;
            final long b = (long)24 * 60 * 60 * 1000;
            System.out.println(a / b);
            //way 2
            final long a1 = 24 * 60 * 60 * 1000 * 1000L;
            final long b1 = 24 * 60 * 60 * 1000L;
            System.out.println(a1 / b1);
        }
    
    0 讨论(0)
  • 2021-01-15 16:19

    Plain number in java considered as int. You need to append L to convert to long. Without L a =500654080, which is wrong.

     final long a= 24 * 60 * 60 * 1000 * 1000L;// Append L
    
    0 讨论(0)
  • 2021-01-15 16:23

    You can use BigInteger or Long:

    public static void main(String[] args) {
            final BigInteger a = new BigInteger("24");
            //multiply by creating big integers....
            final BigInteger b = new BigInteger("60")
    
            System.out.println(a.divide(b));
     }
    
    0 讨论(0)
提交回复
热议问题