gpt4 book ai didi

java - 奇怪的结果增加了一个超过其最大值的短路

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:09:25 25 4
gpt4 key购买 nike

当我执行这段代码时,它给出的 s 值为 -7616。为什么这样?这是因为在将数据从 int 或其他东西转换为 short 时丢失了数据吗?

public static void main(String[] args) {
// TODO code application logic here
short s=0;
int x=123456;
int i=8;
s +=x;
System.out.println(s);

}

最佳答案

你只是溢出了 short 的最大值:

short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.

当有这样的溢出时会发生什么等同于这个算法:

/** Returns an integer which is equal to the short obtained by the ((short) n) conversion */
public static int int2short(int n) {
int sign = n > 0 ? 1 : -1;
int increment = sign * (Short.MAX_VALUE - Short.MIN_VALUE + 1);
for ( ; n > Short.MAX_VALUE || n < Short.MIN_VALUE ; n -= increment);
return n;
}

关于java - 奇怪的结果增加了一个超过其最大值的短路,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27747043/

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