乘法发生溢出

编程入门 行业动态 更新时间:2024-10-25 04:15:19
本文介绍了乘法发生溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 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.

我的问题是-

  • 这对我使用的编译器有影响吗,m2 还是 m3?
  • 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 * ....

    更多推荐

    乘法发生溢出

    本文发布于:2023-11-30 05:25:11,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1648869.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:乘法   发生

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!