for循环应该从1开始吧
by cokkie @ 2023-08-15 13:39:11
```
#include <bits/stdc++.h>
int a[12][12];
int main() {
memset(a, 0, sizeof(a));
int n, x = 1, y = 1, t;
scanf("%d", &n);
t = a[1][1] = 1;
while (t < n * n) {//<=改成<
while (y + 1 <= n && !a[x][y + 1])//if改成while
a[x][++y] = ++t;
while (x + 1 <= n && !a[x + 1][y])
a[++x][y] = ++t;
while (y - 1 >= 1 && !a[x][y - 1])
a[x][--y] = ++t;
while (x - 1 >= 1 && !a[x - 1][y])
a[--x][y] = ++t;
}
for (int i = 1; i <= n; i++) {//从1到n
for (int j = 1; j <= n; j++)
printf("%3d", a[i][j]);
printf("\n");
}
return 0;
}
```
by yangzichen1203 @ 2023-08-15 13:45:18
问题注释里给了,~~有用给个关注呗~~
```cpp
#include <bits/stdc++.h>
using namespace std;
int a[12][12];
int main() {
// memset(a, 0, sizeof(a));
// 不必多此一举
int n, x = 0, y = 0, t; // 这里跟输出一样,从零开始
scanf("%d", &n);
t = a[0][0] = 1;
while (t < n * n)
{ // 这里用while而不是if是因为每次不仅仅只走一步
while (y + 1 < n && !a[x][y + 1])
a[x][++y] = ++t;
while (x + 1 < n && !a[x + 1][y])
a[++x][y] = ++t;
while (y - 1 >= 0 && !a[x][y - 1])
a[x][--y] = ++t;
while (x - 1 >= 0 && !a[x - 1][y])
a[--x][y] = ++t;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
printf("%3d", a[i][j]);
printf("\n");
}
return 0;
}
```
by XuYueming @ 2023-08-15 13:49:00
解决了,谢谢各位
by EkSulfur @ 2023-08-15 14:46:15