如何在C ++中的for循环中更新单独的变量?

问题描述 投票:0回答:1

我想用A-J的边距打印2D数组中的值。我的问题是,边距不会从A开始增加。

我曾尝试在循环中移动++k,但空白处仅重复“ A”。

const int SIZE = 10;
int array_2D[SIZE][SIZE];   // declaring here for context; array was created in
                            // a separted function

for (int i = 0; i < SIZE; ++i)
{
    int k = 65;
    cout << char(k) << " | ";
    ++k;

    for (int j = 0; j < SIZE; ++j)
    {
        cout << setw(2) << setfill('0') << array_2D[i][j] << "   ";     
    }
    cout << endl;    
}

我希望输出为:

A | 00   08   15   01   10   05   19   19   03   05   
B | 06   00   02   08   02   12   16   03   08   17   
C | 12   05   00   14   13   03   02   17   19   16   
D | 08   07   12   00   10   13   08   20   16   15   
E | 04   12   03   14   00   05   02   12   14   09   
F | 08   05   03   18   18   00   04   02   10   19   
G | 17   16   11   03   09   07   00   03   05   09   
H | 07   06   11   10   11   11   07   00   14   09   
I | 10   04   05   15   17   01   07   17   00   09   
J | 05   20   07   04   18   19   19   03   10   00

但是我明白了:

A | 00   08   15   01   10   05   19   19   03   05   
A | 06   00   02   08   02   12   16   03   08   17   
A | 12   05   00   14   13   03   02   17   19   16   
A | 08   07   12   00   10   13   08   20   16   15   
A | 04   12   03   14   00   05   02   12   14   09   
A | 08   05   03   18   18   00   04   02   10   19   
A | 17   16   11   03   09   07   00   03   05   09   
A | 07   06   11   10   11   11   07   00   14   09   
A | 10   04   05   15   17   01   07   17   00   09   
A | 05   20   07   04   18   19   19   03   10   00
c++ arrays multidimensional-array
1个回答
4
投票

您在循环中的每次迭代中都将k重置为65。您需要将初始化移到循环外,即

int k = 65;
for (int i = 0; i < SIZE; ++i)
    {
        cout << char(k) << " | ";
        ++k;


       for (int j = 0; j < SIZE; ++j)
        {

            cout << setw(2) << setfill('0') << array_2D[i][j] << "   "; 

            // array is size [10][10]
            // array was created in a separate function

        }
        cout << endl; 

    }
© www.soinside.com 2019 - 2024. All rights reserved.