Java整数超出范围

编程入门 行业动态 更新时间:2024-10-25 02:18:41
本文介绍了Java整数超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在学习Java,并且正在尝试一些小程序. 我对此有疑问:

I'm learning Java and I'm trying little programs. I have a problem with this one:

/* Compute the number of cubic inches in 1 cubic mile. */ class Inches { public static void main(String args[]) { int ci; int im; im = 5280 * 12; ci = im * im * im; System.out.println("There are " + ci + " cubic inches in cubic mile."); } }

输出为:

There are 1507852288 cubic inches in cubic mile.

我知道整数的宽度(以位为单位)为32,因此范围是: -2,147,483,648至2,147,483,647

I known the width in bits for a integer is 32, so the range is: -2,147,483,648 to 2,147,483,647

为什么输出1507852288? 应该是2,147,483,647.

Why is the output 1507852288? It should be 2,147,483,647.

谢谢.

推荐答案

当结果超过int的最大值时,则溢出,即整数溢出.您可能最好使用long而不是int.

When the result crosses the maximum values of an int then it is overflowed ie, integer overflow. You may better want to use long instead of int.

您可能有兴趣阅读: Java中的整数上溢和下溢. /a>

You may be interested to read: Integer overflow and underflow in Java.

算术整数运算以32位精度执行.什么时候 运算的结果值大于32位( 一个int变量可以容纳的最大大小),然后仅取低32位 考虑到这一点,高阶位将被丢弃.当MSB (最高有效位)为1,则该值被视为负数.

Arithmetic integer operations are performed in 32-bit precision. When the resultant value of an operation is larger than 32 bits (the maximum size an int variable can hold) then the low 32 bits only taken into consideration and the high order bits are discarded. When the MSB (most significant bit) is 1 then the value is treated as negative.

更多推荐

Java整数超出范围

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

发布评论

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

>www.elefans.com

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