byte byteChallenge = 68;
short shortChallenge = 190;
int intChallenge = 2147483647;
long longChallenge = (50000L + 10L * (byteChallenge + shortChallenge + intChallenge));
long longChallengeX = 50000L + 10L * ((long) byteChallenge + (long) shortChallenge + (long)
intChallenge);
System.out.println(longChallenge);
System.out.println(longChallengeX);
我得到的输出是:
-21474783910
21474889050
最佳答案
棘手的部分是 int intChallenge = 2147483647
常量,它是正 int
的最大值(请参阅 Integer.MAX_VALUE
)。
当您执行byteChallenge + ShortChallenge + intChallenge
时,它是一个int
算术语句,结果为integer overflow 。在您的示例中,整数溢出结果是负数。
当您执行(long)byteChallenge +(long)shortChallenge +(long)intChallenge
时,它是long
算术。由于 long
支持比 int
大得多的值,因此不会溢出。
关于java - 为什么在下面的代码中,长类型变量在转换之后和转换之前给出不同的答案,因为两者都是长类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60326291/