0

作业问题是编写一个程序,将课堂考试的所有分数相加并求平均值。

我有两个问题。要找到平均值,您必须将总分除以应试人数。我不知道如何记录有多少应试者。

获取平均值的方法是在 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; 

  }
4

1 回答 1

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;
于 2012-10-23T04:51:38.477 回答