简体   繁体   中英

How to calculate average test score

The homework problem is to write a program that adds together all the scores from a class exam and find the average.

I have two questions. To find the average, you have to divide the total score by the number of test takers. I don't know how to record how many test takers there are.

Does the method for getting the average go in the while loop or outside the while loop?

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; 

  }

just add a count variable for every read

int count=0

while(true) {
  int score = readInt("enter the test score: ");
  if (score == SENTINEL) break;  
  total += score; 
  count++;
}

the calculate the average

double avg = (double)total/count;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM