簡體   English   中英

計算嵌套循環中隨機數的平均值?

[英]Calculating the average of random numbers in a nested loop?

int num = (int)(Math.random() * 50) + 50;
double total = 0;
for (int row = 1; row <= 5; row++) {
  System.out.println();
  System.out.println("Grades for student #" + row);
  for (int col = 0; col < 10; col++) {
    num = (int)(Math.random() * 50) + 50;
    System.out.print(num + ", ");
    total += num * 1.0;
  }

  System.out.println();
  double average = total / 10;
  System.out.println("Average for student is " + average);
}

我需要找到每個學生的平均成績。 等級是隨機生成的。 該代碼打印出第一行數據的正確平均值,但其他 4 行是錯誤的。

您需要在每次運行的外循環中將total重置為 0。


for (int row=1; row<=5; row++) {
        double total = 0;  // <-- Move this inside the loop.
        System.out.println();
        System.out.println("Grades for student #" + row);
        for (int col = 0; col<10; col++) {
            double num = (int)(Math.random()*50)+50;
            System.out.print(num+ ", ");
            total += num; // no need to multiply by 1.0
        }
         
         System.out.println();
         double average = total/10;
         System.out.println("Average for student is " + average);         
}

暫無
暫無

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

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