家庭作业的问题是编写一个程序,将课程考试中的所有分数加在一起,找到平均分。
我有两个问题。要找到平均值,您必须将总分除以考生数。我不知道如何记录有多少考生。
获取平均值的方法是在while循环中还是在while循环之外?
import acm.program.*;
public class AvgScore extends ConsoleProgram {
public void run(){
println("This program averages the test scores of an exam until the SENTINEL is entered .");
int total = 0;
while(true) {
int score = readInt("enter the test score: ");
if (score == SENTINEL) break;
total += score;
}
println("the average for the class was");
}
private static final int SENTINEL = -1;
}
答案 0 :(得分:1)
只需为每次读取添加一个计数变量
int count=0
while(true) {
int score = readInt("enter the test score: ");
if (score == SENTINEL) break;
total += score;
count++;
}
计算平均值
double avg = (double)total/count;