查找 C++ 中矩阵的平均向量
假设我们有一个 M x N 阶矩阵,则我们必须要找出给定矩阵的平均向量。因此,如果矩阵如下所示 −
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
则平均向量是 [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 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP