2017-04-25 5 views
2

高調波のような複数の演算の結果を配列に取り込むにはどうすればいいですか:高調波= 1 + 1/2 + 1/3 + 1/4 ....... + 1/nの 私の不完全なバージョンは次のようになります。複数の結果をJavaの配列に保存

public static void main(String[] args) { 
     int x=1, harmonic=0, y=2; 
     int[] n; 
     n = new int[]; 

     // for populating the array ?!?!?! 
     do {n = {x/y}} 
     y++; 
     while (y<=500); 

     //for the sum for loop will do... 
     for (int z=0; z<=n.length; z++){ 
      harmonic += n[z]; 
      } 
     System.out.println("Harmonic sum is: " + harmonic); 
    } 

答えて

1

2物事あなたがトンをWAN /切り捨てられた値を必要とし、あなたがそのコレクションの代わりに、配列のために使うべきいけないので、...あなたは、ダブルデータ型を使用する必要があります。

public static void main(String[] args) { 

    double x = 1, harmonic = 0, y = 2; 
    List<Double> arc = new ArrayList<>(); 

    do { 
     arc.add(x/y); 
     y++; 
    } while (y <= 500); 

    for (Double double1 : arc) { 
     harmonic += double1; 
    } 
    System.out.println("Harmonic sum is: " + harmonic); 
} 

出力は次のようになります。

ハーモニック合計です:5.792823429990519

編集:

使用してストリーム:私は初めで午前

double streamedHarmonic = arc.stream().mapToDouble(Double::doubleValue).sum(); 
+0

まだl基本的なものを稼いでいるので、私は配列でそれをしようとしていたのです。私はあなたの解決策を勉強します。ありがとう ! – dragos

関連する問題