0

I'm really puzzled by this. I'm dividing two positive numbers and getting a negative result (I'm using Java).

long hour = 92233720368L / (3600 * 1000000 );

I got as result -132.

But if I divide them as two long numbers, I get the right result:

long hour1 = 92233720368L / (3600000000L ); 

Then I get as result: 25

I'm wondering why it occurs...

Thank you in advance! :)

Earthling
  • 35
  • 2
  • 8

2 Answers2

5

You must add L at the end of 3600 or 1000000:

Example:

long hour = 92233720368L / (3600 * 1000000L );

Here's what's hapenning:

System.out.println(3600 * 1000000); // Gives -694967296 because it exceeds the max limit of an integer size. So 92233720368L / -694967296 = -132

That's exactly what's happening in your division, the dominator is an integer and is considered as negative number for the reason I stated above. So in order to consider the multiplication result of type long you should add L after 3600 or after 1000000

CMPS
  • 7,733
  • 4
  • 28
  • 53
2

It interprets 3600 and 10000000 as type int which cannot hold enough information to represent their product, and so you get a different number. You'd have to declare them both as type long to get the correct result.

jhobbie
  • 1,016
  • 9
  • 18