How to calculate the average value of a two-dimensional…

Calculate the average of a two-dimensional array by first finding the sum of all elements in the array and then dividing by the total number of elements. Below is an example code:

int[,] array = new int[,]
{
    { 1, 2, 3 },
    { 4, 5, 6 },
    { 7, 8, 9 }
};

int rows = array.GetLength(0); // 获取二维数组的行数
int cols = array.GetLength(1); // 获取二维数组的列数

int sum = 0;
for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < cols; j++)
    {
        sum += array[i, j];
    }
}

double average = (double)sum / (rows * cols);
Console.WriteLine("平均值为:" + average);

The output is 5.0.

bannerAds