给同学们写一个一眼能看懂的简单代码
2025-04-28 11:10:06
发布于:浙江
2阅读
0回复
0点赞
最外层的while,每一次循环“转一圈”
#include <iostream>
using namespace std;
int a[105][105];
int main() {
int n;
cin >> n;
int num = 1;
int left = 0, right = n - 1, top = 0, bottom = n - 1; // top代表最上面一行,bottom代表最下面熠杭
while (left <= right && top <= bottom) {
for (int i = left; i <= right; i++) a[top][i] = num++;
top++;
for (int i = top; i <= bottom; i++) a[i][right] = num++;
right--;
for (int i = right; i >= left; i--) a[bottom][i] = num++;
bottom--;
for (int i = bottom; i >= top; i--) a[i][left] = num++;
left++;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << a[i][j];
if (j != n - 1) cout << ' ';
}
cout << '\n';
}
return 0;
}
这里空空如也
有帮助,赞一个