C ++中矩阵的均值和中位数

在这个问题中,我们得到大小为n * n的2D数组。我们的任务是创建一个程序,该程序将在C ++中打印矩阵的均值和中值。

平均值是设定日期的平均值。在矩阵中,平均值是矩阵中所有元素的平均值。

平均值= (矩阵中所有元素的总和)/(矩阵中元素的数量)

中位数是排序数据集的最中间元素。为此,我们将必须对矩阵的元素进行排序。

中位数计算为

如果n为奇数,则中位数=矩阵[n / 2] [n / 2]

如果n是偶数,则中位数=((matrix [(n-2)/ 2] [n-1])+(matrix [n / 2] [0]))/ 2

示例

用来说明我们解决方案工作原理的程序

#include <iostream>
using namespace std;
const int N = 4;
int calcMean(int Matrix[][N]) {
   int sum = 0;
   for (int i=0; i<N; i++)
      for (int j=0; j<N; j++)
         sum += Matrix[i][j];
      return (int)sum/(N*N);
   }
   int calcMedian(int Matrix[][N]) {
      if (N % 2 != 0)
         return Matrix[N/2][N/2];
      if (N%2 == 0)
         return (Matrix[(N-2)/2][N-1] + Matrix[N/2][0])/2;
}
int main() {
   int Matrix[N][N]= {
      {5, 10, 15, 20},
      {25, 30, 35, 40},
      {45, 50, 55, 60},
      {65, 70, 75, 80}};
   cout<<"Mean of the matrix: "<<calcMean(Matrix)<<endl;
   cout<<"Median of the matrix : "<<calcMedian(Matrix)<<endl;
   return 0;
}

输出结果

Mean of the matrix: 42
Median of the matrix : 42