45.将3×3二维数组转置,并输出

//1、定义一个3*3的二维数组
//2、输入内容,并在屏幕中输出
//3、运用for循环嵌套将数组转置,并输出

 
(1)我的程序:运用中间量交换
-错误版:转置算法有问题,需要好好模拟一下
#include<iostream>
using namespace std;

int main()
{
    int temp;
    int a[3][3];
    cout<<"please input 9 numbers: "<<endl;

    for(int i=0;i<3;i++)//用于输入内容
    {
        for(int j=0;j<3;j++)
        {
            cin>>a[i][j];
        }
    }

    for(int m=0;m<3;m++)//用于输出原矩阵
    {
        for(int n=0;n<3;n++)
        {
            cout<<a[m][n]<<" ";
        }
        cout<<endl;
    }
    cout<<endl;

    for(int p=0;p<3;p++)//用于将数组转置
    {
        for(int q=0;q<3;q++)
        {
            temp=a[p][q];
            a[p][q]=a[q][p];
            a[q][p]=temp;
        }
    }

    for(int x=0;x<3;x++)//用于输出转置后矩阵
    {
        for(int y=0;y<3;y++)
        {
            cout<<a[x][y]<<" ";
        }
        cout<<endl;
    }
    return 0;
}

-正确版:将转置算法改正

for(int p=0;p<3;p++)//用于将数组转置
    {
        for(int q=0;q<p;q++)//这里有改动
        {
            temp=a[p][q];
            a[p][q]=a[q][p];
            a[q][p]=temp;
        }
    }​

(2)运用中间数组实现:

#include<iostream>
using namespace std;

int main()
{
    int temp;
    int a[3][3];
    int b[3][3];//设置中间数组用于转置
    cout<<"please input 9 numbers: "<<endl;

    for(int i=0;i<3;i++)//用于输入内容
    {
        for(int j=0;j<3;j++)
        {
            cin>>a[i][j];
        }
    }

    for(int m=0;m<3;m++)//用于输出原矩阵
    {
        for(int n=0;n<3;n++)
        {
            cout<<a[m][n]<<" ";
        }
        cout<<endl;
    }
    cout<<endl;

    for(int p=0;p<3;p++)//用于将数组转置
    {
        for(int q=0;q<3;q++)
        {
              b[q][p]=a[p][q];
        }
    }

    for(int x=0;x<3;x++)//用于输出转置后矩阵
    {
        for(int y=0;y<3;y++)
        {
            cout<<b[x][y]<<" ";
        }
        cout<<endl;
    }
    return 0;
}

(3)间接转置:存入数组后,间接输出转置数组

#include<iostream>
using namespace std;

int main()
{
    int temp;
    int a[3][3];
    cout<<"please input 9 numbers: "<<endl;

    for(int i=0;i<3;i++)//用于输入内容
    {
        for(int j=0;j<3;j++)
        {
            cin>>a[i][j];
        }
    }

    for(int m=0;m<3;m++)//用于输出原矩阵
    {
        for(int n=0;n<3;n++)
        {
            cout<<a[m][n]<<" ";
        }
        cout<<endl;
    }
    cout<<endl;

    for(int x=0;x<3;x++)//用于输出转置后矩阵
    {
        for(int y=0;y<3;y++)
        {
            cout<<a[y][x]<<" ";//间接输出转置矩阵
        }
        cout<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/jixiaowu/p/3899935.html