Long Division in Java not working as expected -


class longdiv{ public static void main(string [] args){      final long x = 24*60*60*1000*1000;     final long y = 24*60*60*1000;     system.out.println(x/y); } } 

although expected answer 1000, javac gives 5. reason?

the long x creating isn't value expected. in integer range. create longs, use:

final long x = 24l*60l*60l*1000l*1000l; final long y = 24l*60l*60l*1000l; system.out.println(x/y); 

the x computed, in integer range, 500654080. divided y ( = 86400000), results in 5.794607407407407.... java truncates decimal part causes 5.

by adding l after number literal, tell compiler compile long instead of int. value x expected 86400000000. compiled int.

we can reproduce wrong value x (500654080) truncating int:

// first correct long x = 24l*60l*60l*1000l*1000l; /* x = `86400000000`; */ // truncate x &= 0xffffffffl; // again: don't forget l suffix /* x = `500654080` */ 

Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -