zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C++矩阵转置「建议收藏」

C++ 建议 收藏 矩阵 转置
2023-06-13 09:12:25 时间

大家好,又见面了,我是你们的朋友全栈君。

C++矩阵转置

 看了很多网山有关矩阵转置的代码,大部分还用了中间变量,本人亲测矩阵转置代码无误,望对广大C++初学者有所帮助!

题目如下: 写一个函数,使给定的一个二维数组(3×3)转置,即行列互换。

Input

一个3×3的矩阵

Output

转置后的矩阵(每两个数字之间均有一个空格)

Sample Input

1 2 3 4 5 6 7 8 9 Sample Output

1 4 7 2 5 8 3 6 9

代码如下:

#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
#include <array>
#include <algorithm>
using namespace std;
//int a[3][3] = { {1,2,3}, {4,5,6}, {7,8,9} };
int a[3][3];
//int temp;
void main() {
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            cin >> a[i][j];
            cout << " ";
        }
        cout << endl;
    }
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            cout << a[j][i]<<" ";   
        }
        cout << endl;
    }
}
先定义一个int 类型的3x3的矩阵a,然后用cin输入,cout输出,输入的时候是按照a[i][j]输入,输出的时候两个for循环还是位置不变,只要将a[i][j]变成a[j][i]输出即可,包含这么多头文件是因为习惯性先把可能用到的头文件尽可能都写进去,同时在输出的for循环内部for循环结束时用了一个cout << endl ,确保最后以矩阵的形式输出。

运行结果:

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/149118.html原文链接:https://javaforall.cn