简体   繁体   中英

Java calculating average of numbers from another file

public void computeAverage(String [] names, int [] scores, char [] grades){
    int av = 0;
    for (int i = 0; i < names.length; i++)
        av = (scores[i]++ / 26);
    System.out.print(av);

}

Hey guys, Above is my code to read a list of test scores and compute their average. There are 26 test scores. I am having trouble, Please help! Thanks

The problem here is that you keep writing over the av variable during each iteration of the loop. Also, it looks like you don't needs the names and grades arrays as parameters, as you're not using them. This should work better:

public void computeAverage(int [] scores)
{
    double average = 0;
    for (int i = 0; i < scores.length; i++)
    {
        average += scores[i];
    }

    average /= scores.length;

    System.out.print(average);
}

Let's break this down:

  • You need to loop through your entires scores array and sum each score to a running total

  • You need to then divide by total number of scores. As @cliff.meyers pointed out, that is the definition of an average

  • As a side note, you are looping against name.length, but indexing into scores. That is bad.

  • You are dividing by a hard coded constant. That is also bad.

  • You don't need names or grades in the function to calculate averages.

Try adding them all first, then dividing by the total number. That's how you calculate an average...

You need to add the contributions to the running tally:

av += (scores[i] / 26.0);

Perhaps even better to divide by names.length , and even better to leave the division to the end. Finally, be careful with integer division, which might not do what you think it does.

public static int computAverage(int[] scores)
{
    long sum = 0;
    for(int i : scores)
    sum += i;
    return sum / scores.length;
}

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