你可以通过以下代码实现C++矩阵的转置:
#include <iostream>
const int rows = 3;
const int cols = 3;
void transposeMatrix(int matrix[rows][cols], int result[cols][rows]) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[j][i] = matrix[i][j];
}
}
}
int main() {
int matrix[rows][cols] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int result[cols][rows];
transposeMatrix(matrix, result);
std::cout << "Original Matrix:" << std::endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
std::cout << "Transposed Matrix:" << std::endl;
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
std::cout << result[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
在上面的代码中,transposeMatrix
函数用于计算矩阵的转置,并将结果存储在result
数组中。在main
函数中,我们定义了一个3x3的矩阵matrix
,并调用transposeMatrix
函数来计算转置矩阵,并输出原始矩阵和转置矩阵。