|
|
发表于 2023-10-9 12:35:24
|
显示全部楼层
这段代码存在一些问题,主要是数组下标越界的问题。修改后的代码如下:
- #include <iostream>
- using namespace std;
- int a[22][22];
- int main() {
- int n, s = 1, r = 1, l = 1, now = 2;
- a[l][r] = 1;
- cin >> n;
- while (now <= n * n) {
- while (a[l][r + 1] == 0 && r + 1 <= n) {
- a[l][++r] = now++;
- }
- while (a[l + 1][r] == 0 && l + 1 <= n) {
- a[++l][r] = now++;
- }
- while (a[l][r - 1] == 0 && r - 1 >= 1) {
- a[l][--r] = now++;
- }
- while (a[l - 1][r] == 0 && l - 1 >= 1) {
- a[--l][r] = now++;
- }
- }
- for (int i = 1; i <= n; i++) {
- for (int j = 1; j <= n; j++) {
- cout << a[ i][j];
- if (j < n) {
- cout << " ";
- }
- }
- cout << endl;
- }
- return 0;
- }
复制代码
主要问题在于数组下标越界,需要注意的是数组下标从1开始,而不是从0开始。同时,需要保证数组下标不越界,即不能小于1或大于n。 |
|