两个整数的乘法溢出导致负数

编程入门 行业动态 更新时间:2024-10-23 20:29:50
本文介绍了两个整数的乘法溢出导致负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

考虑Java语言规范中的这个片段。

Consider this snippet from the Java language specification.

class Test { public static void main(String[] args) { int i = 1000000; System.out.println(i * i); long l = i; System.out.println(l * l); } }

输出

-727379968 1000000000000

为什么(i * i)的结果 -727379968 ?理想情况下它应该是1000000000000。

Why is the result -727379968 for (i*i)? Ideally it should be 1000000000000.

我知道Integer的范围是从-2147483648到2147483647.所以显然1000000000000 不在给定范围内。

I know the range of Integer is from –2147483648 to 2147483647. so obviously 1000000000000 is not in the given range.

为什么结果会变成 -727379968 ?

推荐答案

Java(就像现在的大多数计算机架构一样)使用了一种名为 二的补充算术 ,它使用整数的最高有效位表示数字为负数。如果你乘以两个大数字,你最终会得到一个如此大的数字,它设置最高位,结果最终为负数。

Java (like most computer architectures these days) uses something called two's complement arithmetic, which uses the most significant bit of an integer to signify that a number is negative. If you multiply two big numbers, you end up with a number that's so big it sets that highest bit, and the result ends up negative.

更多推荐

两个整数的乘法溢出导致负数

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

发布评论

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

>www.elefans.com

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