簡體   English   中英

Java:如何多次在循環中一起添加變量

[英]Java: How to add variable in a loop together, multiple times

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);

  }
} 

大家好,我想知道如何在一個循環中計算出一個值,然后每次循環結束時(以及計算出的值)將它們平均在一起。 我無法理解這個概念,我嘗試在上面的代碼中做到這一點,但我不太清楚。

如您所見,有兩個while循環,並且在其中一個循環內計算出一個隨機值(距離)。 因此,本質上,我需要將距離平均在一起,但是我無法想象如何將每次計算的距離相加成一個數。 假設該循環經過了一次並輸出了一個奇異的距離,我將如何與舊的一起添加一個新的距離(對於新的循環),然后繼續進行每次試驗呢?

您只需將每個試驗的總距離相除即可。

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);
  }
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM