Java 如何计算平均考试分数
家庭作业问题是编写一个程序,将课堂考试的所有分数相加,得出平均值Java 如何计算平均考试分数,java,average,Java,Average,家庭作业问题是编写一个程序,将课堂考试的所有分数相加,得出平均值 我有两个问题。要计算平均分,你必须将总分除以参加考试的人数。我不知道如何记录有多少考生。 获取平均值的方法是在while循环内还是在while循环外 import acm.program.*; public class AvgScore extends ConsoleProgram { public void run(){ println("This program averages the test scores
我有两个问题。要计算平均分,你必须将总分除以参加考试的人数。我不知道如何记录有多少考生。
获取平均值的方法是在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;
}
只需为每次读取添加一个计数变量
int count=0
while(true) {
int score = readInt("enter the test score: ");
if (score == SENTINEL) break;
total += score;
count++;
}
计算平均值
double avg = (double)total/count;
为什么不在while循环中增加一个计数器变量?您应该跟踪输入到程序中的值的数量(而不是SENTINEL),一旦退出循环,就应该使用该计数来计算平均值。不过提示:当您进行除法时,请将其中一个数转换为双精度。谢谢。有没有不使用count++计算平均值的方法?我还没有看到这一点,我想知道是否有另一种方法可以利用上面的信息来实现这一点?1)整数除法。2) 向新手推荐非标准java变量命名。您忘记了
int count=0在while(true)
之前,我甚至没有声明变量它只是一段代码。在这里,让我改变一下它,再投一次反对票来解决家庭作业!只是开玩笑。。。但气垫船是对的,好好教他们!