简体   繁体   English

C# 计算平均值会增加一个额外的数字

[英]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.我是 C# 的新程序员,在这个网站上是新的,找不到关于这个主题的类似帖子,如果它已经被覆盖,很抱歉。

As part of a video course, I was instructed to create a console "APP" that calculates an average of students' scores.作为视频课程的一部分,我被指示创建一个控制台“APP”来计算学生的平均分数。 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?我不明白的是为什么 C# 为学生增加了另一个额外的数字? so the user enters 5 and I get to put a score 6 times...所以用户输入5,我得到6次得分......

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.迭代器变量“ totalStudents ”从 0 开始,因此您的 while 循环条件应仅更改为“<”,同时使用“ studentNumber ”变量来计算平均值。

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) .简短的回答是您应该使用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.假设总共有 3 名学生,请告诉我每个循环中totalStudents的值是多少。 Please try to work it out before continuing, this is an essential skill to understand as a beginner.请在继续之前尝试解决它,这是作为初学者理解的基本技能。

First loop: totalStudents = 0第一个循环: totalStudents = 0
Second loop: totalStudents = 1第二个循环: totalStudents = 1
Third loop: totalStudents = 2第三个循环: totalStudents = 2
Fourth loop: totalStudents = 3第四个循环: totalStudents = 3

In summary: When starting loop X, totalStudents equals X-1总结:当开始循环 X 时, totalStudents等于 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 .对于每个循环(假设 3 个学生),告诉我totalStudents的值。

First loop: totalStudents = 1第一个循环: totalStudents = 1
Second loop: totalStudents = 2第二个循环: totalStudents = 2
Third loop: totalStudents = 3第三个循环: totalStudents = 3
Fourth loop: totalStudents = 4第四个循环: totalStudents = 4

In summary: When finishing loop X, totalStudents equals X总结:当完成循环 X 时, totalStudents等于 X

At the end of the third loop, the while will check to see if it needs to start another loop.在第三个循环结束时, while将检查是否需要启动另一个循环。 To check this, it checks if totalStudents <= studentNumber .要检查这一点,它会检查是否totalStudents <= studentNumber

We established in my example that studentNumber is 3. But what is the value of totalStudents after the third loop has executed?在我的示例中,我们确定studentNumber为 3。但是在第三个循环执行后, totalStudents的值是多少? (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.由于您现在知道totalStudentsstudentNumber的值,因此您可以看到totalStudents <= studentNumber将评估为true ,因此将启动第四个循环。

But you don't want this.但你不想要这个。 You want it to stop after studentNumber amount of loops.您希望它在studentNumber循环数之后停止。
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 .因此,正确的while评估应该使用小于运算符: 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 totalStudents => amount_of_students_you_have_entered_so_far
  • studentNumber => amount_of_students_you_will_enter_in_total 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.就我个人而言,我会使用studentCounterstudentTotal来表示一个是向上计数的值,另一个是这个计数值应该达到的最大限制。

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 ).我怀疑您无法发现该错误的部分原因是因为您使用“总数”一词来指代输入的学生人数totalStudents ),而您使用“数字”来指代您的学生总数将输入 ( 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 <也许是因为在 while 循环中你放了小于或等于 5,所以它会在学生总数中增加 1 直到达到 5,并且它会在第五个中增加 1,使其成为 6。就是这样,如果你只是改变它应该可以正常工作<= 只是 <

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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