查詢 C++ 中矩陣的平均向量


假設我們有一個 M x N 階矩陣,則我們必須要找出給定矩陣的平均向量。因此,如果矩陣如下所示 −

123
456
789

則平均向量是 [4, 5, 6],因為每一列的平均值分別為 (1 + 4 + 7)/3 = 4、(2 + 5 + 8)/3 = 5 和 (3 + 6 + 9)/3 = 6

透過此示例,我們可以輕鬆地確定,如果計算每一列的平均值,那麼就能得到平均向量。

示例

 線上演示

#include<iostream>
#define M 3
#define N 3
using namespace std;
void calculateMeanVector(int mat[M][N]) {
   cout << "[ ";
   for (int i = 0; i < M; i++) {
      double average = 0.00;
      int sum = 0;
      for (int j = 0; j < N; j++)
      sum += mat[j][i];
      average = sum / M;
      cout << average << " ";
   }
   cout << "]";
}
int main() {
   int mat[M][N] = {{ 1, 2, 3 },
      { 4, 5, 6 },
      { 7, 8, 9 }
   };
   cout << "Mean vector is: ";
   calculateMeanVector(mat);
}

輸出

Mean vector is: [ 4 5 6 ]

於: 2019-12-17 更新

已檢視 131 次

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.