我必须编写一个程序,在二维数组中显示以下模式:
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
我的代码:
#include <iostream>
#include<iomanip>
using namespace std;
#define SIZE 5
int main()
{
int i, j, n, x;
int array[SIZE][SIZE];
int left, top;
left = 0;
n = 1;
cout<<"Enter dimension of array pattern:";
cin>>x;
while(x<1||x>6){
cout<<"Invalid entry. Enter a number greater than 0 and less than 6";
cin>>x;
}
top = x-1;
for(i=1;i<=x/2;i++,left++,top--){
for(j=left;j<=top;j++,n++)
array[left][j]=n;
for(j=left+1;j<top;j++,n++)
array[j][top]=n;
for(j=top;j>left;j--,n++)
array[top][j]=n;
for(j=top;j>left;j--,n++)
array[j][left]=n;
}
for(i=0; i<x; i++)
{
for(j=0; j<x; j++)
{
cout<<setw(3)<<array[i][j];
}
cout<<endl;
}
system("pause");
return 0;
}
它适用于偶数输入,但将最后一个值作为奇数的垃圾。\n \n 输入
5
输出
1 2 3 4 5
16 17 18 19 6
15 24700383242 20 7
14 23 22 21 8
13 12 11 10 9
任何帮助将不胜感激。