이 문제에서는 크기가 n*n인 2D 배열이 제공됩니다. 우리의 임무는 행렬의 평균과 중앙값을 C++로 출력하는 프로그램을 만드는 것입니다.
평균 설정된 날짜의 평균입니다. 행렬에서 평균은 행렬의 모든 요소의 평균입니다.
평균 =(행렬의 모든 요소의 합)/(행렬의 요소 수)
중앙값 정렬된 데이터 세트의 가장 중간 요소입니다. 이를 위해 행렬의 요소를 정렬해야 합니다.
중앙값은 다음과 같이 계산됩니다.
n이 홀수이면 median =matrix[n/2][n/2]
n이 짝수이면 중앙값 =((행렬[(n-2)/2][n-1])+(행렬[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