简体   繁体   中英

C# calculating an average adds an extra number

I'm a new programmer to C# and new on this website and couldn't find a similar post on the subject, so sorry if it was already covered.

As part of a video course, I was instructed to create a console "APP" that calculates an average of students' scores. the user inputs the total amount of students, then each individual score, and then the sum is divided by the number of students. what I can't understand is why C# adds another extra number to the students? so the user enters 5 and I get to put a score 6 times...

class Program
{
 

    static void Main(string[] args)
    {
        
        int totalScores= 0;
        int totalStudents = 0;
        int number;

        Console.WriteLine("how many students are there?");
        int studentNumber = int.Parse(Console.ReadLine());
        

        while(totalStudents <= studentNumber)
        {
            Console.WriteLine("enter your student score");
            string studentScore = Console.ReadLine();
            if (int.TryParse(studentScore, out number))
            {
                totalScores += number;
                totalStudents += 1;
            }
            else
            {
                Console.WriteLine("you did not enter a number");
            }
            
        }
        int avarage = totalScores / totalStudents;

        Console.WriteLine("the average is" + average);
    }

    
}

This is what I see in the console: console

I'm sure I'm missing something... any advice?

The iterator variable ' totalStudents ' starts with 0, so your while loop condition should be changed to only '<', also use the ' studentNumber ' variable for calculating the Average.

while(totalStudents < studentNumber)
{
    Console.WriteLine("enter your student score");
    string studentScore = Console.ReadLine();
    if (int.TryParse(studentScore, out number))
    {
        totalScores += number;
        totalStudents += 1;
    }
    else
    {
        Console.WriteLine("you did not enter a number");
    }
    
}
int avarage = totalScores / studentNumber;

The short answer

The short answer is that you should use while(totalStudents < studentNumber) . But let's explore why.

The long answer

I want you to focus on this point in time:

while(totalStudents <= studentNumber)
{
    // <------ HERE

    Console.WriteLine("enter your student score");
    string studentScore = Console.ReadLine();
    
    // rest of code omitted      
}

In other words, this is after you've decided to register another student, but before you've registered the student.

Assuming 3 students total, tell me what the value of totalStudents is in every loop. Please try to work it out before continuing, this is an essential skill to understand as a beginner.

First loop: totalStudents = 0
Second loop: totalStudents = 1
Third loop: totalStudents = 2
Fourth loop: totalStudents = 3

In summary: When starting loop X, totalStudents equals X-1

Note: I added a fourth loop in my list because your current code runs for one loop extra, and I want to show you what's happening to cause that fourth loop.

Now let's repeat this exercise but focus on another point in time:

while(totalStudents <= studentNumber)
{
    Console.WriteLine("enter your student score");
    string studentScore = Console.ReadLine();
    
    // if block omitted      

    // <------ HERE
}

In other words, this is after you've decided to register another student, and after you've registered the student. For each loop (assume 3 students), tell me the value of totalStudents .

First loop: totalStudents = 1
Second loop: totalStudents = 2
Third loop: totalStudents = 3
Fourth loop: totalStudents = 4

In summary: When finishing loop X, totalStudents equals X

At the end of the third loop, the while will check to see if it needs to start another loop. To check this, it checks if totalStudents <= studentNumber .

We established in my example that studentNumber is 3. But what is the value of totalStudents after the third loop has executed? (hint: look at the above values I made you list).

Since you now know the value of both totalStudents and studentNumber , you can see that totalStudents <= studentNumber will evaluate to true , and thus a fourth loop will be started.

But you don't want this. You want it to stop after studentNumber amount of loops.
Another way to phrase this is that another loop should only be started when the amount of students you have currently registered is LESS THAN the total amount of students you wish to register. When they are equal, you do NOT want to start another loop.

Therefore, the correct while evaluation should use the less than operator: totalStudents < studentNumber .

What's in a name?

As a good tip, try to use better descriptive names for your variables. I suggest the following renaming:

  • totalStudents => amount_of_students_you_have_entered_so_far
  • studentNumber => amount_of_students_you_will_enter_in_total

These are quite long names, but I'm making them very descriptive and easy to understand, because you are a beginner. Now let's revisit your code again (containing the bug), using the new names:

while(amount_of_students_you_have_entered_so_far <= amount_of_students_you_will_enter_in_total)
{        
    // rest of code omitted      
}

It's much clearer now to see that your evaluation is flawed.

I admit these names are overly long. But if you struggle parsing the meaning of code, it's better to be overly descriptive than it is to make it harder to guess. The experience will come with time, and then you can reduce your variable name length.

Personally, I would've used studentCounter and studentTotal to indicate that one is a value that counts up, and the other is the max limit that this counting value should reach.

I suspect that part of the reason you couldn't spot the bug is because you used the word "total" to refer to the number of entered students ( totalStudents ), and you used "number" to refer to the total amount of students you will enter ( studentNumber ). You've swapped the words around.

Maybe its because in the while loop you put less or equal 5, so its gonna add one to total students until it reaches 5 and it will add one extra to the fifth one making it 6. thats it, itshould work correctly if you just change <= to just <

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