C++矩阵转置

来源:互联网 发布:中文域名重要性 编辑:程序博客网 时间:2024/05/21 07:11

C++矩阵转置

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

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

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 ,确保最后以矩阵的形式输出。

运行结果:
这里写图片描述

原创粉丝点击