C++ 中矩阵的平均数和中位数
此问题中,给定一个大小为 n*n 的二维数组。我们的任务是创建一个程序,该程序将打印 C++ 中矩阵的平均数和中位数。
平均数是数据集的平均值。在矩阵中,平均数是矩阵所有元素的平均值。
平均数 = (矩阵所有元素之和)/(矩阵元素数量)
中位数是有序数据集的中间元素。为此,我们需要对矩阵的元素进行排序。
中位数计算为:
如果 n 为奇数,中位数 = matrix[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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP