Wrong Multiplication Result

I am trying to understand why this multiplication leads to an incorrect value:

long max = (60 * 24 * 60 * 60 * 1000);

That should = 5,184,000,000

But in my Java program this is = 889 032 704

Any idea why this is so?

+4
source share
2 answers

All the values ​​that you multiply are equal int, so the result intthat is passed in longafter the overflow has already occurred. Make one of the factors a longto multiply them with 64b commands

Try

long max = (60L * 24L * 60L * 60L * 1000L);

The suffix Lindicates that a constant is a value long, not a constant int.

language specification speaks

Integer long, ASCII L l (ell); int (§4.2.1).

- .

int int s:

(§5.1.2) , :

  • double, double.
  • , float, float.
  • , long, long.
  • int
+11

. int ( ), "" .

long, 60L, , (long) 60:

long max = (long) 60 * 24 * 60 * 60 * 1000;

, .

+5

Source: https://habr.com/ru/post/1538108/


All Articles