Warm tip: This article is reproduced from serverfault.com, please click

Outputting averages from arrays C# based upon class average on a test

发布于 2021-10-13 22:42:06

I am trying to output the overall class average on a test using a program which makes use of arrays. The program is meant to be for a class of 12 students. When I try to input all data I need, I don't get the average for the class as a whole. The problem obviously lies in the average calculator itself but seeing as I am a beginner I have little clue how to fix it. Any help would be appreciated. Just to reiterate, I am looking for a solution on how to fix my average calculator to give the class average as an overall. I have entered my code below. I hope I have been specific.

string[] studentnames = new string[12];
        int[] testscore = new int[12];

        int i;
        int index;
        double average;
        int total = 0;

        //title

        Console.Write("\n\nStudent lists:\n");

        Console.Write("******************\n");

        //asks user to input names

        Console.Write("Enter student names:\n");

        for (i = 1; i < 12; i++)

        {

            Console.Write("Student name {0} : ", i);

            studentnames[i] = (Console.ReadLine());

            //asks user to enter student's test score

            Console.Write("Please enter their test score: ");

            testscore[i] = Convert.ToInt32(Console.ReadLine());

        }

        //outputs all values user has entered

        Console.WriteLine("\nStudent marks: ");

        for (i = 1; i < 12; i++)

        {

            Console.WriteLine("Name: ");

            Console.WriteLine("{0} ", studentnames[i]);

            Console.WriteLine("Test score: ");

            Console.WriteLine("{0} ", testscore[i]);

        }

        for (index = 1; index < 12; index++)
        {
            total = total + testscore[index];
            average = total / 12;

            Console.WriteLine("The class average was: " + average);
        }
        Console.ReadKey();
Questioner
user17109321
Viewed
0
Nigel 2021-10-14 07:31:45

The division by the total needs to be after the for loop.

This:

for (index = 1; index < 12; index++)
{
    total = total + testscore[index];
    average = total / 12;

    Console.WriteLine("The class average was: " + average);
}

Needs to become:

for (index = 1; index < 12; index++)
{
    total = total + testscore[index];
}
average = ((double)total) / 12;
Console.WriteLine("The class average was: " + average);

Another problem: your for loops start at index 1. C# uses 0 based indexing. I assume you are trying to calculate the average for 12 students, not 11.

Also, for the love of god please stop writing the number 12. If you absolutely must hard-code it, use a constant.

Edit: I've updated my answer to account for flydog's comment