2

我必须编写一个程序,在二维数组中显示以下模式:

1  2  3  4  5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9

我的代码:

    #include <iostream>
    #include<iomanip>

    using namespace std;
    #define SIZE 5

     int main()
     {
         int i, j, n, x;
         int array[SIZE][SIZE];
         int left, top;

         left = 0;
         n    = 1;

         cout<<"Enter dimension of array pattern:";
         cin>>x;
         while(x<1||x>6){
             cout<<"Invalid entry. Enter a number greater than 0 and less than 6";
cin>>x; 
         }

         top  = x-1;

         for(i=1;i<=x/2;i++,left++,top--){

            for(j=left;j<=top;j++,n++) 
            array[left][j]=n;

            for(j=left+1;j<top;j++,n++)
             array[j][top]=n;

            for(j=top;j>left;j--,n++)
            array[top][j]=n;

            for(j=top;j>left;j--,n++)
            array[j][left]=n;

         }

         for(i=0; i<x; i++)
         {
             for(j=0; j<x; j++)
             {
                 cout<<setw(3)<<array[i][j];

             }
        cout<<endl;

         }

    system("pause");
    return 0;
    }

它适用于偶数输入,但将最后一个值作为奇数的垃圾。\n \n 输入

5

输出


1  2  3  4  5
16 17 18 19 6
15 24700383242 20 7
14 23 22 21 8
13 12 11 10 9

任何帮助将不胜感激。

4

1 回答 1

2

对于奇数,您永远不会更改中心值,因此它将未初始化。然后将其读出是未定义的行为,通常表现为获取垃圾值。您可以通过扩展循环以在该中心字段上运行来修复它:

for (i = 1; i <= (x / 2)+1; i++, left++, top--) {

或者,由于很容易计算出它将具有什么值,因此您可以在循环后手动填写:

if (x%2 == 1)
    array[x/2][x/2] = x * x;

另外,当用户输入一个无效数字时,不要忘记读入一个新数字:

while (x < 1 || x>6) {
    cout << "Invalid entry. Enter a number greater than 0 and less than 6";
    cin >> x;
}
于 2019-12-13T10:25:48.127 回答