计算嵌套循环中随机数的平均值?

huangapple go评论58阅读模式
英文:

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("学生 #" + 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);
}
英文:
int num = (int)(Math.random() * 50) + 50;
double total = 0;
for (int row = 1; row &lt;= 5; row++) {
  System.out.println();
  System.out.println(&quot;Grades for student #&quot; + row);
  for (int col = 0; col &lt; 10; col++) {
    num = (int)(Math.random() * 50) + 50;
    System.out.print(num + &quot;, &quot;);
    total += num * 1.0;
  }

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

I need to find the average grade for each student. Grades are randomly generated. The code prints out the correct average for the first line of data but the other 4 are wrong.

答案1

得分: 2

你需要在每次运行外部循环时将 total 重置为 0。


for (int row=1; row<=5; row++) {
    double total = 0;  // <-- 将此行移到循环内部。
    System.out.println();
    System.out.println("学生 #" + row + " 的成绩");
    for (int col = 0; col<10; col++) {
        double 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);         
}
英文:

You need to reset total to 0 in the outer loop for each run.


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

</details>



huangapple
  • 本文由 发表于 2020年10月19日 08:02:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/64419510.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定