简体   繁体   English

Java中的正数除法,负数

[英]Positive division, negative result in Java

I'm really puzzled by this. 我对此感到非常困惑。 I'm dividing two positive numbers and getting a negative result (I'm using Java). 我将两个正数相除并得到一个负数结果(我正在使用Java)。

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

I got as result -132. 结果是-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 然后我得到的结果是:25

I'm wondering why it occurs... 我想知道为什么会发生...

Thank you in advance! 先感谢您! :) :)

You must add L at the end of 3600 or 1000000 : 您必须在36001000000的末尾添加L

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 因此,为了考虑long类型的乘法结果,应该在36001000000之后加上L

It interprets 3600 and 10000000 as type int which cannot hold enough information to represent their product, and so you get a different number. 它将3600和10000000解释为int类型,它不能容纳足够的信息来表示其产品,因此您将获得一个不同的数字。 You'd have to declare them both as type long to get the correct result. 您必须将它们都声明为long类型以获得正确的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM