c#:如何找到多个平均值之间的最高平均值

时间:2018-04-12 20:03:24

标签: c#

我的代码如下,目的是获取学生人数,以及他们的名字和每个5分,然后为每个学生显示:

  • 总和
  • 平均
  • 超过50的商标数量 (以上提到的所有作品)

这是我无法工作的部分: 我必须显示平均分最高的学生的姓名和标记。所以它必须记住每个人的平均值并找到最高的,我该怎么做?

static void Main(string[] args)
    {
        int total = 0;
        int gt50Count = 0;

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

        for (int y = 1; y <= students; y++)
        {
            Console.WriteLine("Enter student name");
            string name = Console.ReadLine();

            for (int x = 1; x <= 5; x++)
            {
                Console.WriteLine("Enter your mark");
                int mark = int.Parse(Console.ReadLine());

                if (mark > 100 || mark < 0)
                {
                    Console.WriteLine("Invalid mark,Enter your mark again");

                    int newmark = int.Parse(Console.ReadLine());
                    mark = newmark;
                }

                total += mark;

                if (mark >= 50)
                {
                    gt50Count++;
                }
            }
            Console.WriteLine("sum = " + total);

            double average = (total / 5.0) * 1.00;
            Console.WriteLine("average = " + average);

            Console.WriteLine("Greater or equal to 50 count = " + gt50Count);
            Console.ReadLine();

            total = 0;
            gt50Count = 0;
        }
    }

1 个答案:

答案 0 :(得分:2)

  

所以它必须记住每个人的平均值并找到最高的,我该怎么做?

一般模式如下:循环遍历元素,获取当前元素。我们已经有了最高元素吗?如果不是,则当前元素自动为最高。如果是,那么当前元素是否更高?如果是,那么它是迄今为止最高的元素。

bool gotHighest = false;
T highest = default(T);
some_looping_construct
{
  T current = code that gets the current T.
  if (gotHighest)
  {
    if (current > highest)
      highest = current
  }
  else 
  {
    highest = current;
    gotHighest = true;
  }
}
// Now if gotHighest is false, there was no highest element.
// If it is true, then highest is the highest element.

您可以将此模式应用于您的计划吗?