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

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

Calculating the average of random numbers in a nested loop?

问题

  1. int num = (int)(Math.random() * 50) + 50;
  2. double total = 0;
  3. for (int row = 1; row <= 5; row++) {
  4. System.out.println();
  5. System.out.println("学生 #" + row + " 的成绩");
  6. for (int col = 0; col < 10; col++) {
  7. num = (int)(Math.random() * 50) + 50;
  8. System.out.print(num + ", ");
  9. total += num * 1.0;
  10. }
  11. System.out.println();
  12. double average = total / 10;
  13. System.out.println("学生的平均成绩为 " + average);
  14. }
英文:
  1. int num = (int)(Math.random() * 50) + 50;
  2. double total = 0;
  3. for (int row = 1; row &lt;= 5; row++) {
  4. System.out.println();
  5. System.out.println(&quot;Grades for student #&quot; + row);
  6. for (int col = 0; col &lt; 10; col++) {
  7. num = (int)(Math.random() * 50) + 50;
  8. System.out.print(num + &quot;, &quot;);
  9. total += num * 1.0;
  10. }
  11. System.out.println();
  12. double average = total / 10;
  13. System.out.println(&quot;Average for student is &quot; + average);
  14. }

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。

  1. for (int row=1; row<=5; row++) {
  2. double total = 0; // <-- 将此行移到循环内部。
  3. System.out.println();
  4. System.out.println("学生 #" + row + " 的成绩");
  5. for (int col = 0; col<10; col++) {
  6. double num = (int)(Math.random()*50)+50;
  7. System.out.print(num+ ", ");
  8. total += num; // 无需乘以 1.0
  9. }
  10. System.out.println();
  11. double average = total/10;
  12. System.out.println("学生的平均成绩为 " + average);
  13. }
英文:

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

  1. for (int row=1; row&lt;=5; row++) {
  2. double total = 0; // &lt;-- Move this inside the loop.
  3. System.out.println();
  4. System.out.println(&quot;Grades for student #&quot; + row);
  5. for (int col = 0; col&lt;10; col++) {
  6. double num = (int)(Math.random()*50)+50;
  7. System.out.print(num+ &quot;, &quot;);
  8. total += num; // no need to multiply by 1.0
  9. }
  10. System.out.println();
  11. double average = total/10;
  12. System.out.println(&quot;Average for student is &quot; + average);
  13. }
  14. </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:

确定