乘法发生溢出 [英] Overflow occurs with multiplication

查看:70
本文介绍了乘法发生溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

long m = 24 * 60 * 60 * 1000 * 1000;

上面的代码会产生溢出并且没有打印出正确的结果.

The above code creates overflow and doesn't print the correct result.

long m2 = 24L * 60 * 60 * 1000 * 1000;
long m3 = 24 * 60 * 60 * 1000 * 1000L;

以上两行打印出正确的结果.

The above 2 lines print the correct result.

我的问题是-

  1. 这对我使用的编译器有影响吗,m2 还是 m3?
  2. java 是如何开始乘法的?从左到右还是从右到左?是先计算 24*60 还是 1000*1000?

推荐答案

我会使用 m2 行而不是 m3 行.

I would use the m2 line instead of the m3 line.

Java 从从左到右计算乘法运算符*,所以24 * 60 先求值.

Java evaluates the multiplication operator * from left to right, so 24 * 60 is evaluated first.

碰巧24 * 60 * 60 * 1000(一个1000)不会溢出,所以当你乘以1000L(第二个1000),乘积前提升为long,这样就不会发生溢出.

It just so happens that 24 * 60 * 60 * 1000 (one 1000) doesn't overflow, so that by the time you multiply by 1000L (the second 1000), the product is promoted to long before multiplying, so that overflow doesn't take place.

但正如您在评论中提到的,在乘以最后一个 long 数字之前,更多因素可能导致 int 数据类型溢出,从而产生错误答案.最好在 m2 中为第一个(最左边的)数字使用 long 文字,以避免从一开始就溢出.或者,您可以将第一个文字转换为 long,例如(长)24 * 60 * ....

But as you mentioned in your comments, more factors can cause overflow in the int data type before multiplying the last long number, yielding an incorrect answer. It's better to use a long literal for the first (left-most) number as in m2 to avoid overflow from the start. Alternatively, you can cast the first literal as a long, e.g. (long) 24 * 60 * ....

这篇关于乘法发生溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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