求二维数组的平均值,可以先求出二维数组中所有元素的总和,然后再除以二维数组的元素个数。下面是一个示例代码:
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);
输出结果为:5.0