回 帖 发 新 帖 刷新版面

主题:用C++语言编程,在Visual C++环境下调试完成矩阵的运算

[em10][em10][em10]急急急急急急急急急急急急急急急啊啊啊啊啊啊
(1)将螺旋方阵存放到n*n的二维数组中并把它输出,要求由程序自动生成螺旋方阵(而不是人为地初始化或逐个赋值)。螺旋方阵的形式为:
             1   12   11  10
             2   13   16   9
             3   14   15   8  
             4    5    6   7      


(2) 求此螺旋矩阵的转置矩阵并显示;
(3) 求此转置矩阵对角线的和。

回复列表 (共1个回复)

沙发

#include<iostream.h>
#include<iomanip.h>

int main()
{
    int matrix[102][102],wide,x,y,nx,ny,n=1,direct=1;
    for(int i=0;i<102;i++)
        for(int j=0;j<102;j++)
            matrix[i][j]=0;
        cout<<"输入矩阵宽度"<<endl;
        cin>>wide;
        if(wide<=0||wide>100)
            cout<<"宽度必须大于0,小于100"<<endl;
        else for(int i=1;i<=wide;i++)
            for(int j=1;j<=wide;j++)
                matrix[i][j]=-1;
            ny=nx=x=y=1;
            while(n<=wide*wide)
            {
                if(matrix[x][y]==-1)
                    matrix[x][y]=n++;
                switch(direct)//运动方向
                {
                case 1:
                    nx=x+1;
                    break;
                case 2:
                    ny=y+1;
                    break;
                case 3:
                    nx=x-1;
                    break;
                case 4:
                    ny=y-1;
                    break;
                default:
                    break;
                }
                
                if(matrix[nx][ny]>=0)//改变方向
                {
                    direct++;
                    if(direct==5)
                        direct=1;
                    nx=x;
                    ny=y;
                }
                
                x=nx;
                y=ny;
                
            }
            for(i=1;i<=wide;i++)
            {
                for(int j=1;j<=wide;j++)
                    cout<<setw(2)<<matrix[i][j]<<" ";
                cout<<endl;
            }
            return 0;
            
}

我来回复

您尚未登录,请登录后再回复。点此登录或注册