Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/380.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java如何遍历一个双精度数组并舍入到最接近的整数_Java_Arrays_Rounding - Fatal编程技术网

Java如何遍历一个双精度数组并舍入到最接近的整数

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

我试过几件事。我需要遍历一个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.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]);
}