问题描述
我在java中有double数组,我需要转换成short数组。有什么想法吗?
解决方法
double[] d = { 2,3.2,4.8,123456789.123 };
short[] s = new short[d.length];
for (int i = 0; i < d.length; i++) {
s[i] = (short) d[i];
}
System.out.println("short output: " + Arrays.toString(s));
---------------------
Result: short output: [2,3,4,-13035]
这真的是你需要的吗?精度损失对你来说不重要吗?
,您想如何打印...? 从数组中打印单个值时,您可以将 double 转换为 short,如下所示:
public class array {
public static void main(String[] args){
double [] array = new double[] {132.45612,9556.456789876,6513.987652,123456789.123};
System.out.println((short)array[3]);
}
}
这输出 -13035
通过更改 sysout 中的数字,您应该会得到不同的结果。