我的代码如下,目的是获取学生人数,以及他们的姓名和每个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;
}
}
所以它必须记住每个人的平均值并找到最高的,我该怎么做?
一般模式是这样的:遍历元素,获取当前元素。 我们已经有了最高的元素吗? 如果否,则当前元素自动为最高元素。 如果是,当前元素是否更高? 如果是,那么它是迄今为止最高的元素。
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.
您可以将此模式应用于您的程序吗?