[英]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.