gpt4 book ai didi

java - 无法理解Java溢出和编译错误逻辑

转载 作者:行者123 更新时间:2023-12-02 11:07:16 25 4
gpt4 key购买 nike

我是Java新手,正在研究int溢出!
在玩一些整数时,我意识到结果很奇怪

    int x = 2147483647 + 1;    
x == > - 2147483648

int x = 2147483647 + 2;
x ==> -2147483647

int x = 2147483647 + 2147483647;
x ==> -2

int x = 2147483647 + 2147483648;
**compile error**

我认为整数溢出不会导致任何编译错误。另外,我很难理解如何计算溢出的输出(例如,为什么int x = 2147483647 + 1//x ==> -2147483648)
有人可以解释这些结果的逻辑吗?

谢谢!!

最佳答案

language spec:

The largest decimal literal of type int is 2147483648 (2^31).

All decimal literals from 0 to 2147483647 may appear anywhere an int literal may appear. The decimal literal 2147483648 may appear only as the operand of the unary minus operator - (§15.15.4).

It is a compile-time error if the decimal literal 2147483648 appears anywhere other than as the operand of the unary minus operator; or if a decimal literal of type int is larger than 2147483648 (2^31).


您不能将2147483648用作 int文字,因为 int文字是 int表达式,因此必须具有 int值。但是2147483648太大,无法用作 int值。

关于java - 无法理解Java溢出和编译错误逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61986441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com