文章
19
粉丝
225
获赞
20
访问
53.3k
值得注意的是最后的输出格式,%-3d是左对齐3位,不足的用空格补齐
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int main() {
int n;
scanf("%d", &n);
int** a = (int**)malloc(sizeof(int*) * n);
for (int i = 0; i < n; i++)
a[i] = (int*)malloc(sizeof(int) * n);
int t = 1;
int on = 0, down = n, left = 0, right = n;
while (on < down && left < right) {
for (int i = on; i < down; i++)//左
a[i][left] = t++;
for (int i = left + 1; i < right; i++)//下
a[down-1][i] = t++;
for (int i = down - 2; i >= on; i--)//右
a[i][right-1] = t++;
for (int i = right - 2; i > left; i--)//上
a[on][i] = t++;
on++, down--, left++, right--;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%-3d ", a[i][j]);
}
printf("\n");
}
return 0;
}
登录后发布评论
暂无评论,来抢沙发