0

宿題の問題は、クラス試験のすべてのスコアを合計して平均を求めるプログラムを作成することです。

2つの質問があります。平均を求めるには、合計スコアを受験者数で割る必要があります。受験者の数を記録する方法がわかりません。

平均を取得する方法は、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 に答える