2016-08-15 2 views
0

아래 코드는 프로그램을 실행할 때 pi에 가까운 번호를 제공합니다. 평가판 당 던진 다트의 수에 대한 사용자 입력이 필요하며이를 사용하여 pi에 가까운 번호를 찾습니다. 특정 수의 시험을 위해 코드를 실행해야하지만 제대로 작동하지 않는 것처럼 보일 수 있습니다. 어떻게해야합니까?루프가 다른 루프를 반복하는 방법?

System.out.print("How many darts per trial? "); 
    int darts = in.nextInt(); 
    System.out.print("How many trials? "); 
    int trials = in.nextInt(); 

    //The code below this represents 1 trial 
    for(int i = 0; i < darts; i++) 
    { 
     xInt[i] = (Math.random() * (upper - lower)) + lower; 
     yInt[i] = (Math.random() * (upper - lower)) + lower; 
     c2[i] = Math.pow(xInt[i], 2) + Math.pow(yInt[i], 2); 
     c[i] = Math.sqrt(c2[i]); 

     if(c[i] <= 1) 
     { 
      hits++;     
     }      
    } 
    double answer = 4 * ((double)hits/(double)darts);    
    System.out.println(answer); 

은 내가가 루프 시련에 대한 (아래 참조), 다음은 모든 답변을 추가하고 그것은 인쇄해야

for(int n = 0; n < trials; n++) 
    { 
     for(int i = 0; i < darts; i++) 
     { 
      xInt[i] = (Math.random() * (upper - lower)) + lower; 
      yInt[i] = (Math.random() * (upper - lower)) + lower; 
      c2[i] = Math.pow(xInt[i], 2) + Math.pow(yInt[i], 2); 
      c[i] = Math.sqrt(c2[i]); 
      if(c[i] <= 1) 
       hits++; 
     } 
    } 

    double answer = 4 * ((double)hits/(double)darts);    
    System.out.println(answer); 

합이 같은 것을 인쇄 추가 한 경우 때를 완료되었습니다.

Trial [1]: pi = 3.11341744 
Trial [2]: pi = 3.04824237 
Trial [3]: pi = 3.33281081 
Trial [4]: pi = 3.40901039 
+0

변수'darts'의 값을 늘리시겠습니까? –

+0

_... 다른 for-loop 내부에서 작동하지만 작동하지 않음 "_ - 작업 한 내용을 표시하고 작동하지 않는 부분을 설명하십시오. [도움말]을 읽고 사용법을 배우십시오. 이 사이트 –

+0

명확히하기 위해 - 이것은 * N * 번 실행하고 싶거나, 더 많은 다트를 추가하기를 원하는 지정 다트의 구체적인 숫자가있는 파이의 몬테카를로 추정입니까? – Makoto

답변

1

히트 = 0을 추가하여 각 평가판의 히트 수를 재설정해야합니다. 루프에 대한 시련 직후 계산 및 인쇄 문을 for 루프 내부로 이동합니다. 이처럼 :

for(int n = 0; n < trials; n++) 
{ 
    hits=0; 
    for(int i = 0; i < darts; i++) 
    { 
     xInt[i] = (Math.random() * (upper - lower)) + lower; 
     yInt[i] = (Math.random() * (upper - lower)) + lower; 
     c2[i] = Math.pow(xInt[i], 2) + Math.pow(yInt[i], 2); 
     c[i] = Math.sqrt(c2[i]); 
     if(c[i] <= 1) 
      hits++; 
    } 
    double answer = 4 * ((double)hits/(double)darts);    
    System.out.println(answer); 
} 

내가 제대로 이해 해요 경우이를 수정해야합니다.

+0

정말 고마워요! – Maya

관련 문제