2017-04-25 1 views
2

에 저장 어떻게 고조파 합계와 같은 여러 연산의 결과로 배열을 채울 수 있습니까? 고조파 = 1 + 1/2 + 1/3 + 1/4 ....... + 1/n를 내 불완전한 버전은 다음과 같습니다 : 당신이 잘린 값을 필요/t를 완 해달라고 이후복수형 결과를 자바 배열

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 일이 ... 당신이 이중 데이터 형식을 사용해야합니다, 당신은 사용해야하는 컬렉션을 대신 배열 .

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

그리고 아직도 내가 기본을 얻으 려니 배열로 처리하려고했습니다. 나는 당신의 해결책을 연구 할 것입니다. 정말 고마워 ! – dragos