2017-09-14 205 views
0
public class R { 

    public static void main(String[] args) { 
     int n = Integer.parseInt(args[0]); 
     int trials = Integer.parseInt(args[1]); 
     int x = 0; 
     int y = 0; 

     int j = 0; 
     int distance = 0; 

     while (trials>j) { 
      j = j + 1; 
      int i = -1; 
      double counter = 1.0 * distance; 
      double sum = (distance + counter); 
      while (i<=n) { 
       i = i + 1; 
       if (i == n) { 
       distance = ((x*x) + (y*y)); 
       } 
       if (i<n) { 
        int random = (int)(Math.random() * 4 + 1); 
        if (random == 1) x = x + 1; 
        if (random == 2) y = y + 1; 
        if (random == 3) x = x - 1; 
        if (random == 4) y = y - 1; 
       } 
      }   
     } 
     double average= (sum)/(trials); 
     System.out.println("mean " + "squared " + "distance " + "= " + average); 

    } 
} 

嘿,我想知道如何在一個循環內計算一個值,然後每一次循環結束(以及計算中的值)將它們平均在一起。我無法圍繞這個概念包裹頭腦,我試圖在上面的代碼中做這件事,但我無法弄清楚。Java:如何在一個循環中一起添加變量多次

正如你所看到的那樣,有兩個while循環,並且在其中一個循環中計算了一個隨機值(距離)。所以基本上我需要將距離平均在一起,但我無法想象如何將每次計算的距離一起添加到一個數字中。假設循環經過一次並輸出一個單獨的距離,那麼我將如何與舊的一起添加一個新距離(用於新循環),然後繼續爲每個試驗做這些?

+0

有一個變量來保存一個累計和另一個計數器。然後只需計算每個循環後的平均值。 – MC10

+0

您好,您是否在尋求關於如何計算多條路徑的平均距離的問題或具體幫助的概念性幫助? –

+0

我想是的概念幫助。我剛剛根據第一條評論修復了我的代碼,並認爲我想出了它,但是似乎Java使用一個在循環內聲明的變量並在循環外部使用該變量來解決平均計算問題。 –

回答

0

你只需要劃分每次試驗的總距離。

public class R { 

    public static void main(String[] args) { 
     int n = Integer.parseInt(args[0]); 
     int trials = Integer.parseInt(args[1]); 
     int x = 0; 
     int y = 0; 

     int j = 0; 
     int distance = 0, distance_total = 0; 

     while (trials>j) { 
      j = j + 1; 
      int i = -1; 
      distance = 0; 
      while (i<=n) { 
       i = i + 1; 
       if (i == n) { 
       distance += ((x*x) + (y*y)); 
       } 
       if (i<n) { 
        int random = (int)(Math.random() * 4 + 1); 
        if (random == 1) x = x + 1; 
        if (random == 2) y = y + 1; 
        if (random == 3) x = x - 1; 
        if (random == 4) y = y - 1; 
       } 
      }   
      distance_total += distance; 
     } 
     System.out.println(distance_total/j); 
    } 
} 
+0

非常感謝你。我不知道爲什麼我試圖想想這個問題。我再次編輯了代碼,我認爲它完全可以工作。 –

+0

很高興幫助。如果您對我在代碼中更改的內容有任何疑問,請詢問。 –

相關問題