Why does this not result in 1000? [duplicate]
Possible Duplicate:
Java problem-Whats the reason behind and what will be probable output
long milli=24*60*6开发者_运维问答0*1000;
long micro=24*60*60*1000*1000;
long result=micro/milli;
The result should be 1000 but its not. Why does it work when I use 24*60*60*1000*1000L
?
Can someone tell me the reason for this?
The trouble is that the calculation is done on int
s and then casted to long
, and unfortunately 24*60*60*1000*1000 won't fit in an int
and wraps around. You could do something like
long micro=24L*60*60*1000*1000;
to force the last multiplication to be done on longs.
Easy, if you know, but always a surprise ;)
The literal 1000
is an int
value, so the multiplaction is done with integers and not with longs.
long micro=24*60*60*1000*1000;
is interpreted like
long micro = (long) ((int) 24*60*60*1000*1000);
which is 500654080
instead of 86400000000
Use at least one long literal in your expression, this forces the whole calculation to be done in long
:
long milli=24*60*60*1000;
long micro=24*60*60*1000*1000 * 1L; // forces a calculation in long
long result=micro/milli;
It may be that 24*60*60*1000*1000
is treated as an int and is getting truncated.
To force it to be treated as a long, make one (or all) of the numbers a long by suffixing it with L
:
24L*60L*60L*1000L*1000L
When you tell Java to multiply int
values (and whole number literals are always of type int
unless you append l
or L
), then the result will always be of type int
as well. 24*60*60*1000*1000
results in an overflow, because it's bigger than the biggest possible int
value (Integer.MAX_VALUE
).
Then (after the overflow was "resolved" by cutting of the most significant bits), the value gets assigned to a long
value.
Specifying one of the numbers as long
(1000L
) means that the whole multiplication is done with long
numbers.
Your problem here is that the int
datatype only supports numbers until around 2000000000, while your number is 86400000000, which is about 40 times this number. Thus your multiplication wraps around (discards the highest bits of the result).
So you need to switch to the next larger datatype, long
, by telling Java that at least one of your numbers are intended as such:
long micro=24*60*60*1000*1000L;
Then your result will be right.
This is because you're doing integer (32 bits) arythmetics, and then transform the int result into a long. SInce the numbers are too big, it doesn't work.
Replace by :
long milli=24*60*60*1000L;
long micro=24*60*60*1000*1000L;
long result=micro/milli;
to force the operations do be done with longs.
The maximum value and int can hold is Integer.MAX_VALUE
and your macro value is bigger than an integer can hold and calculation is made on integers so it is being truncated. If you make one of the multipliers long (ending with L or l) it will calculate correctly.
long milli=24*60*60*1000;
long micro=24*60*60*1000*1000L;
long result=micro/milli;
精彩评论