如何从用户输入中找到多维数组中的数字平均值?

  • 本文关键字:数组 数字 平均值 用户 c#
  • 更新时间 :
  • 英文 :


这是我第一次尝试创建多维数组。我让用户输入班级中学生的数量(行(,然后让他们输入他们将输入的分数数量(列(。我现在想将每个学生的所有分数相加,并找到他们的每个平均成绩。我不知道如何分离出每个学生数据的信息。这是我到目前为止所拥有的:

public static void Main(string[] args)
{
int TotalStudents = 0;
int TotalGrades = 0;
int sum = 0;
Console.WriteLine("Enter the number of students: ");
TotalStudents = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the number of grades: ");
TotalGrades = Convert.ToInt32(Console.ReadLine());
int[,] scoresArray = new int[TotalStudents, TotalGrades];
for (int i = 0; i < TotalStudents; i++)
for (int j = 0; j < TotalGrades; j++)
{
Console.Write("Please enter score {0} for student {1}:", j + 1, i + 1);
scoresArray[i, j] = Convert.ToInt32(Console.ReadLine());
sum = sum + Convert.ToInt32(scoresArray[i,j]);
}
double gradePercent = sum / (TotalGrades * 100);
double gradePer100 = gradePercent * 100;
string gradeLetter = "";
if (gradePer100 >= 90)
{
gradeLetter = "A";
}
else if (gradePer100 >= 80 && gradePer100 < 90)
{
gradeLetter = "B";
}
else if (gradePer100 >= 70 && gradePer100 < 80)
{
gradeLetter = "C";
}
else if (gradePer100 >= 60 && gradePer100 < 70)
{
gradeLetter = "D";
}
else
{
gradeLetter = "F";
}
Console.WriteLine("nStudent average score is: " + gradePer100);
Console.WriteLine("nStudent will recieve a " + gradeLetter + " in the class.");
Console.Write("nPress the [ENTER] key to exit.");
Console.ReadLine();
}

您可以像这样创建一个二维数组:

var array = new int[TotalStudents, TotalGrades];

然后填写:

for(int i = 0; i < TotalStudents; i++)
for(int j = 0; j < TotalGrades; j++)
{
Console.Write("Please enter score {0} for student {1}",  j + 1, i + 1);
array[i, j] = Convert.ToInt32(Console.ReadLine());
}

如果分数double则只需new int[TotalStudents, TotalGrades]更改为new double[TotalStudents, TotalGrades]Convert.ToInt32(Console.ReadLine())更改为Convert.ToDouble(Console.ReadLine())

最新更新