为什么在某些情况下将大数字相乘会得出错误的结果? [英] Why in one case multiplying big numbers gives a wrong result?

查看:106
本文介绍了为什么在某些情况下将大数字相乘会得出错误的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎很简单,但我没有任何答案. 当我写的时候:

This might seem simple but I don't have any answer. When I write:

 System.out.println (100 * 1000 * 10000 * 100000);
 System.out.println (100 * 1000 * 10000 * 100000.0);

它返回以下值:

276447232
1.0E14

我知道这与某些数据类型的最大值有关.但是,我想给出一个清晰的答案,为什么它要为两个方程返回这些精确值.如果有人可以向我解释这一点,我将非常感激.

I understand that this has something to do with maximum values of some data types. But I would just like a clear answer as to why it returns these exact values for both equations. If someone can explain this to me I will be very appreciative.

第一次返回与int数据类型的最大值不匹配,这就是为什么我感到困惑的原因.我假设的第二个返回值是double或float值,但我不确定.

The first return doesn't match the maximum value for int datatype, that's why I'm confused. And the second return I'm assuming is a double or float value, but I'm not sure.

推荐答案

在表达式中

System.out.println (100 * 1000 * 10000 * 100000);

参数为int,结果超过了int的允许最大值,即2147483647.这就是我们所说的溢出.根据 Java语言规范

The parameter is an int and the result exceeds the maximum value admissible for an int which is 2147483647. This is what we call an overflow. According to the Java Language Specification

如果整数乘法溢出,则结果是数学乘积的低阶位,以某种足够大的二进制补码格式表示.

If an integer multiplication overflows, then the result is the low-order bits of the mathematical product as represented in some sufficiently large two's-complement format.

取一个数字的N个低阶位等效于计算该数字除以2 ^ N的余数.在我们的情况下,N = 32,因为int存储在32位上.这就是为什么乔恩·斯基特(Jon Skeet)回答

Taking the N low-order bits of a number is equivalent to computing the remainder of the division of this number by 2^N. In our case, N=32 because int are stored on 32 bits. This why Jon Skeet answered by saying

100000000000000 % (2^32)是276447232.

100000000000000 % (2^32) is 276447232.

在表达式

System.out.println (100 * 1000 * 10000 * 100000.0);

三个第一因子100 * 1000 * 10000的乘积给出的1_000_000_000小于最大int值.最后一个乘法导致二进制数值提升,这意味着在这种情况下,1_000_000_000被转换(提升)为double,然后乘以100000.0.

The product of the three first factor 100 * 1000 * 10000 gives 1_000_000_000 which is less than the maximum int value. The last multiplication leads to a Binary Numeric Promotion which means, in this case, that 1_000_000_000 is converted (promoted) to double and then multiplied by 100000.0.

这篇关于为什么在某些情况下将大数字相乘会得出错误的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆