0

いくつか試してみました。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]; 
     }
4

4 に答える 4

1

Math.round を変数に割り当てる必要があります。

これを試して:

for(int i = 0; i < example.length; i++){
    example[i] =  Math.round(example[i]);
}
于 2013-11-05T11:10:55.897 に答える
1
for(int i = 0; i < example.length; i++){
     Math.round(example[i]);
}  

上記のループではMath.round()、変数に値を代入していないため、値が失われます。

の値が必要ない場合はdouble[]、同じ要素に割り当てることができます。したがって、ループは次のようになります。

for(int i = 0; i < example.length; i++){
    example[i] = Math.round(example[i]); // assigning back to same element
}   

それ以外の場合は、別の配列、おそらくint[]. 次に、次のようになります。

int[] roundedValues = new int[example.length];  
for(int i = 0; i < example.length; i++){
        roundedValues[i] = (int) Math.round(example[i]); // into new array
} 
于 2013-11-05T11:11:37.720 に答える
0

これを試すことができます:

 for(int i = 0; i < example.length; i++){
      example[i] = Math.round(example[i]);
 }
于 2013-11-05T11:12:13.347 に答える
0

2 ループは必要ありません。

から返された結果を使用していませんMath.round()

double を int にキャストしようとしています - その必要はありません。

試す:

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]);
} 
于 2013-11-05T11:14:47.713 に答える