简体   繁体   English

Java的负数乘法

[英]Java multiplication of negative numbers

In normal maths terms, -1756046391 * -1291488517 will equal 2267913749295792147. 在正常的数学术语中,-1756046391 * -1291488517将等于2267913749295792147。

When i enter the exact same equation in java, i get the answer: -1756046391 * -1291488517 = 19. 当我在java中输入完全相同的等式时,我得到答案:-1756046391 * -1291488517 = 19。

Can anyone shed any light on this? 任何人都可以对此有所了解吗?

Overflow. 溢出。

Check out Integer.MAX_VALUE. 检查Integer.MAX_VALUE。 An Integer in Java is a 32 bit 2s complement value. Java中的Integer是32位2s补码值。 You can't exceed the MAX_VALUE. 您不能超过MAX_VALUE。

When dealing with very large numbers, you need to make sure the data type you used is big enough to store that number. 处理非常大的数字时,您需要确保您使用的数据类型足以存储该数字。 In java you have these primitive number types: 在java中,您有这些原始数字类型:

type:                      min:                      max:
byte                       -128                       127
short                    -32768                     32767
int              -2,147,483,648             2,147,483,647
long -9,223,372,036,854,775,808 9,223,372,036,854,775,807

So as you can see, your number would just about fit into a long . 所以你可以看到,您的号码将只是放入一个long But you're bound to go over that, so you should probably use the BigInt class instead: 但是你必须要考虑那个,所以你应该使用BigInt类代替:

http://docs.oracle.com/javase/6/docs/api/java/math/BigInteger.html http://docs.oracle.com/javase/6/docs/api/java/math/BigInteger.html

如其他人所说的那样使用long,或者如果这对你的应用程序来说不够,可以考虑使用BigInteger

Post the exact code you used to reproduce this. 发布您用于重现此内容的确切代码。

You are most likely using ints. 你最有可能使用整数。 Use longs, because 2267913749295792147 is too big to fit in an int. 使用long,因为2267913749295792147太大而不适合int。

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

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