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