#include<iostream>
#include <iomanip>
using namespace std;
#define nr 10 //定义矩阵的行和列
#define nl 7
void main()
{
int a1[nr][nl];
int num = 0;
for (int i=0;i<nr;i++)
{
for (int j=0; j<nl; j++)
{
a1[i][j] = num++;
}
}
for (int i=0;i<nr;i++)
{
for (int j=0; j<nl; j++)
{
cout<<setw(2)<<a1[i][j]<<" ";
}
cout<<endl;
}
int row = nr; //行
int col = nl; //列
int oushuda=0;
int m,n;
if (1 == (row & 0x1))
{
m=(row+1)/2;
}
else
{
m=row/2;
oushuda = row-col;
}
if (1 == (col & 0x1))
{
n=(col+1)/2;
}
else
{
n=col/2;
oushuda = col-row;
}
if (0 == row || 0 == col)
{
cout<<"空矩阵"<<endl;
return;
}
for (int i=0,j=0; i<m&&j<n; i++,j++)
{
if (1==row||1==col) //如果只有一行或者一列 直接打印
{
for (int ii=0;ii<row;ii++)
for(int jj=0;jj<col;jj++)
cout<<a1[ii][jj]<<" ";
cout<<endl;
break;
}
if ((i==m-1||j==n-1) && (row & 0x1 || col & 0x1) && oushuda>=0) //如果行和列中有奇数, 并且如果有偶数时,偶数比奇数大
{
if (row == col ) //如果都是奇数
{
cout<<a1[i][j];
break;
}
else if (row>col) //如果行数大于列数
{
for(int m=i;m<row-i;m++)
cout<<a1[m][j]<<" ";
cout<<endl;
break;
}else //如果列数大于行数
{
for(int m=j;m<col-j;m++)
cout<<a1[i][m]<<" ";
cout<<endl;
break;
}
}
for (int x=j; x<col-j-1;x++) //最后一圈之前,正常打印
{
cout<<a1[i][x]<<" ";
}
cout<<endl;
for (int x=i; x<row-i-1;x++)
{
cout<<a1[x][col-j-1]<<" ";
}
cout<<endl;
for (int x=col-1-j; x>j;x--)
{
cout<<a1[row-i-1][x]<<" ";
}
cout<<endl;
for (int x=row-1-i; x>i;x--)
{
cout<<a1[x][j]<<" ";
}
cout<<endl;
}
getchar();
}
顺时针打印矩阵
最新推荐文章于 2024-08-19 17:00:22 发布