[英]How to get average of columns in a 2d array
I have just started using 2D arrays, but can't seem to figure out how to get the average of each column. 我刚刚开始使用2D数组,但似乎无法弄清楚如何获取每一列的平均值。 I am using a for loop to have the user enter the data( a students grade), then a for loop to display the information user entered. 我正在使用for循环让用户输入数据(学生成绩),然后使用for循环显示用户输入的信息。 But after the information is displayed, I want to display the average of each column. 但是在显示信息之后,我想显示每列的平均值。 What should I do get the average of each column? 我应该如何获得每列的平均值?
This is the code I have so far 这是我到目前为止的代码
static void Main(string[] args)
{
double[,] grades = new double[2, 3];
double result;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write("Enter Grade " + (j + 1) + " For Group" + (i + 1) + ": ==>> ");
if (double.TryParse(Console.ReadLine(), out result)) grades[i, j] = result;
else
{
Console.WriteLine("*** INVALID GRADE ENTERED. PLEASE REENTER.");
}
}
}
for (int row = 0; row < 1; row++)
{
Console.WriteLine();
Console.Write(" Group " + (row + 1) + ": ");
Console.WriteLine(" Group " + (row + 2) + ": ");
Console.Write("=========== ===========");
for (int col = 0; col < 3; col++)
{
//String.Format("{0,-10} | {1,-10} | {2,5}",
//make pring for execise 2 Console.Write(string.Format("{0,-5}", grades[row, col]));
Console.WriteLine();
Console.Write(string.Format("{0,-9}", ""));
Console.Write(string.Format("{0,-20}",grades[0, col]));
Console.Write(grades[1,col]);
}
Console.WriteLine();
Console.WriteLine("=========== ===========");
}
Console.WriteLine("\n\npress any key to exit...");
Console.ReadKey();
//print it for exercise 1 myArr[o, column]; myArr[ , column]
}`
If you are looking for a special command that will do it for you, you're out of luck! 如果您正在寻找可以为您执行的特殊命令,那您真不走运! You'll just have to write the code to do it, the same way you would normally average a series of numbers. 您只需要编写代码即可完成此操作,就像通常将一系列数字取平均值一样。 Hint: The number of elements in the 'y' dimension of a 2D array is given by eg grades.GetLength(1)
. 提示:二维数组'y'维度中的元素数量由grades.GetLength(1)
。
To get Average per columns you need to traverse columns for a fixed row and add their values like this: 要获得“每列平均”,您需要遍历固定行的列并添加其值,如下所示:
int columnTotal, average;
for (int row = 0; row < 2; row++)
{
columnTotal = 0;
for (int col = 0; col < 2; col++)
{
columnTotal += grades[row, col];
}
average = columnTotal/2;
Console.WriteLine("Average: {0}", average);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.