五阶魔方阵,对角线相加的c语言实现代码
时间: 2023-08-06 20:11:10 浏览: 143
下面是五阶魔方阵,对角线相加的 C 语言实现代码:
```c
#include <stdio.h>
#define N 5
int main() {
int magic_square[N][N] = {0};
int row = N-1, col = N/2, i, j;
int num = 1;
// 将数字填入魔方阵中
while (num <= N * N) {
magic_square[row][col] = num++;
int next_row = (row + 1) % N;
int next_col = (col + 1) % N;
if (magic_square[next_row][next_col] == 0) {
row = next_row;
col = next_col;
} else {
row = (row - 1 + N) % N;
}
}
// 输出魔方阵并计算对角线之和
int sum1 = 0, sum2 = 0;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
printf("%2d ", magic_square[i][j]);
if (i == j) {
sum1 += magic_square[i][j];
}
if (i + j == N-1) {
sum2 += magic_square[i][j];
}
}
printf("\n");
}
printf("Sum of diagonal 1: %d\n", sum1);
printf("Sum of diagonal 2: %d\n", sum2);
return 0;
}
```
该程序使用了一个 5x5 的二维数组 `magic_square` 存储魔方阵,然后通过遍历填入数字。同时,程序还计算了对角线之和,并输出结果。
阅读全文