你可以通過以下代碼實現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
函數來計算轉置矩陣,并輸出原始矩陣和轉置矩陣。