|
发表于 2020-2-18 21:40:59
|
显示全部楼层
回帖奖励 +1 鱼币
本帖最后由 alexw_h264 于 2020-2-18 21:43 编辑
#include <stdio.h>
#define N 5
int main()
{
int a[N][N] = {
{17, 24, 1, 8, 15},
{23, 5, 7, 14, 16},
{4, 6, 13, 20, 22},
{10, 12, 19, 21, 3},
{11, 18, 25, 2, 9}
};
int i,j;
int row_sum[N], col_sum[N], cross_sum[2], sum_array[N*2+2], *p;
int is_magic_mtx = 1;
//求每行、每列的累加值
for (i = 0; i < N; i++)
{
row_sum[i] = 0;
col_sum[i] = 0;
for (j = 0; j < N; j++)
{
row_sum[i] += a[i][j];
col_sum[i] += a[j][i];
}
}
//求对角线上的累加值
cross_sum[0] = 0;
cross_sum[1] = 0;
for (i = 0; i < N; i++)
{
cross_sum[0] += a[i][N-i-1];
cross_sum[1] += a[i][i];
}
//放在一维数组里
p = sum_array;
for (i = 0; i < N; i++)
{
*p++ = row_sum[i];
}
for (i = 0; i < N; i++)
{
*p++ = col_sum[i];
}
*p++ = cross_sum[0];
*p++ = cross_sum[1];
//判断是否为魔方矩阵
for (i = 0; (i < (2*N+2)) && is_magic_mtx; i++)
{
int cur = sum_array[i];
for (j = i+1; j < (2*N+2); j++)
{
if (sum_array[j] != cur)
{
is_magic_mtx = 0;
break;
}
}
}
if (is_magic_mtx)
{
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
printf("%3d,\t", a[i][j]);
}
printf("\n");
}
}else
{
printf("not a magic matrix");
}
return 0;
} |
|