Simple Java-不断根据我的计数和平均值计算出目标值吗?

问题描述 投票:0回答:2

对于家庭作业,我需要取得未指定的成绩等级(不超过100),获得平均成绩,并显示多少高于或低于平均成绩。我正在尝试使用Sentinal值在放成绩时退出循环。尽管确实退出循环,但它也将Sentinal值作为坡度输入并将其计算为平均值。例如,如果我输入分数“ 50 75 100”,则以-1退出。结果将显示为74.66666666667。我可以看一下为什么要在我的for循环中执行此操作,但是我正在努力寻找一种解决方法。


public class AnalyzeScores {

 public static void main(String[] args) {
     double scores, average;
     int aboveAvg, belowAvg;
     double sum = 0;
     int count = 0;

     Scanner input = new Scanner(System.in);
     double[] scoresList = new double[100];


     for (int i = 0; i < 100; i++) {
         System.out.print("Enter Score " + (i + 1)  + "(negative score exits): ");
         scoresList[i] = input.nextDouble();
         sum = sum + scoresList[i];
         count++;

         if (scoresList[i] < 0) {
            average = (sum / i);
            System.out.println("average is " + average); 
            return;
         }
     }




 }

}
java sum average
2个回答
1
投票

您应该移动这段代码:

         sum = sum + scoresList[i];
         count++;

从if条件之前到if条件之后。


1
投票

这是因为您在计算平均值时将-1放入列表中。您需要先检查输入值是否小于零,然后再将其添加到scoresList

这里是解决此问题的代码(但仍需要一些改进):

public class Main {

    public static void main(String[] args) {
        double scores, average;
        int aboveAvg, belowAvg;
        double sum = 0;
        int count = 0;

        Scanner input = new Scanner(System.in);
        double[] scoresList = new double[100];


        for (int i = 0; i < 100; i++) {
            System.out.print("Enter Score " + (i + 1)  + "(negative score exits): ");
            double score = input.nextDouble();
            if (score >= 0) {
                scoresList[i] = score;
                sum = sum + scoresList[i];
                count++;
            }
            else break;
        }
        average = (sum / count);
        System.out.println("average is " + average);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.