英文:
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 <= 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);
}
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<=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);
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论