Java如何遍历一个双精度数组并舍入到最接近的整数
我试过几件事。我需要遍历一个double数组。并将每个元素四舍五入到最接近的整数。知道我哪里出错了吗Java如何遍历一个双精度数组并舍入到最接近的整数,java,arrays,rounding,Java,Arrays,Rounding,我试过几件事。我需要遍历一个double数组。并将每个元素四舍五入到最接近的整数。知道我哪里出错了吗 for(int i = 0; i < example.length; i++){ Math.round(example[i]); } int[] example1 = new int[example.length]; for(int i=0; i<example1.length; i++) { Math.roun
for(int i = 0; i < example.length; i++){
Math.round(example[i]);
}
int[] example1 = new int[example.length];
for(int i=0; i<example1.length; i++) {
Math.round(example1[i]);
example1[i] = (int) example[i];
}
for(int i=0;i 对于(int i=0;i您需要将Math.round指定给变量
试试这个:
for(int i = 0; i < example.length; i++){
example[i] = Math.round(example[i]);
}
for(int i=0;i
否则,将其放入另一个数组,可能是int[]
。然后,它将如下所示:
for(int i = 0; i < example.length; i++){
example[i] = Math.round(example[i]); // assigning back to same element
}
int[] roundedValues = new int[example.length];
for(int i = 0; i < example.length; i++){
roundedValues[i] = (int) Math.round(example[i]); // into new array
}
int[]roundedValues=newint[example.length];
对于(int i=0;i
您可以尝试以下方法:
for(int i = 0; i < example.length; i++){
example[i] = Math.round(example[i]);
}
for(int i=0;i
您不需要两个循环
您没有使用从Math.round()
返回的结果
您正在尝试将一个双精度转换为整数-无需这样做
尝试:
double[]exmaple=//获取您的double数组
long[]四舍五入=新的long[example.length];
for(int i=0;i您需要将Math.round
的结果分配回aray元素。@marounnaroun,我这样做了=)
for(int i = 0; i < example.length; i++){
example[i] = Math.round(example[i]);
}
double[] exmaple = //get your array of doubles
long[] rounded = new long[example.length];
for (int i=0; i<example.length; i++) {
rounded[i] = Math.round(example[i]);
}