简体   繁体   中英

Java multiplication of negative numbers

In normal maths terms, -1756046391 * -1291488517 will equal 2267913749295792147.

When i enter the exact same equation in java, i get the answer: -1756046391 * -1291488517 = 19.

Can anyone shed any light on this?

Overflow.

Check out Integer.MAX_VALUE. An Integer in Java is a 32 bit 2s complement value. You can't exceed the 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:

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 . But you're bound to go over that, so you should probably use the BigInt class instead:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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