Java中的长整型转换给出不正确的结果
问题描述:
我试图分离出长整数的数字,以便它可以表示为整数数组 Java中的长整型转换给出不正确的结果
12345......888 as [1,2,3,4,......8,8,8]
在通常的方式,我取N%10取出最后一位数字和n/10的人数减少,即
public static void main(String[] args) {
long temp = 111111111111111110L;
while(temp>0){
System.out.println("----------");
System.out.println(temp%10);
System.out.println((int)temp%10);
temp=temp/10;
}
}
TEMP%10给出正确的结果。但它不能直接添加到int列表中。如果我尝试键入强制转换,则在前几次迭代中会得到不正确的结果。 输出
----------
0
-2
----------
1
9
----------
1
-5
----------
1
1
----------
1
9
----------
1
-3
----------
1
-5
----------
1
-7
----------
1
1
----------
1
1
----------
1
1
----------
1
1
----------
1
1
----------
1
1
----------
1
1
----------
1
1
----------
1
1
----------
1
1
我使用的解决办法是
int digitArray[] = new int[somenumber];
String s = Long.toString(n);
for(int i=0;i<s.length();i++){
digitArray[i]=Integer.parseInt(""+s.charAt(i));
}
但我很好奇,为什么类型转换并不在第一种方式工作时数为型铸造是个位数,即井内的长距离。
答
表达式评估规则导致此问题。
你这么做的时候
(int)temp%10
其实大long
价值temp
被强制转换为int
导致integer
溢出,
你的意思
(int)(temp%10)
感谢。我很愚蠢!这样愚蠢的事情;我为自己感到羞耻,我在第一时间犯了这个错误,而且我甚至无法弄清楚。 –