请教高手给编个程序,用C
将自然数按下图所示的次序存到N×N的二维数组A中
举例(5×5的),在数组中这样放
1 2 9 10 25
4 3 8 11 24
5 6 7 12 23
16 15 14 13 22
17 18 19 20 21
你说的是魔方阵的问题吧?我可以发一个我自己写的,没验过输入大奇数会不会造成内存空间失败
#include <iostream.h>
#include <iomanip.h>
void magic(int n)
{
//如果是偶数,返回
if((n % 2 == 0) || n <= 1)
return;
int i, j;
//定义两个矩阵,由它们确定输出结果
int **I, **J;
I = new int*[n];
J = new int*[n];
for (i = 0; i < n; i++)
{
I[i] = new int[n];
J[i] = new int[n];
}
//求矩阵I 和 J 的值
int t = (n - 1) / 2;
for(i = 0; i < n; i ++)
I[0][i] = J[0][n-1-i] = (t + i) % n + 1;
for(i = 1; i < n; i ++)
for(j = 0; j < n; j++)
{
I[i][j] = J[i][n - 1 - j] = I[i - 1][(n - 1 + j)%n];
}
//输出结果,是N * N 的矩阵
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
cout << setw(3) << n * (I[i][j] - 1) + J[i][j] << ' ';
}
cout << endl;
}
// cout << endl << "每行每列之和为: ";
// for (i = 0, t = 0; i < n; i++)
// t += n * (I[0][i] - 1) + J[0][i];
// cout << t << endl;
//释放空间
for(i = 0; i < n; i++)
{
delete []I[i];
delete []J[i];
}
delete []I;
delete []J;
}