C:尽管忽略了初始化和增量表达式,但 for 循环仍在执行,因此始终为 true



上下文:

您好,我正在尝试打印一个 7x6 Connect Four 板,其中每个部分都带有三个下划线|___|。我想创建每个中心下划线 2D 数组的一个元素,以便以后可以更新它。

冲突:

我没有收到任何错误或警告,但我的输出只是|________ ...无限数量的下划线。我已经成功地重写了打印三个下划线的代码,而无需将中心分配到数组中(但是显然这段代码对于制作实际游戏是无用的,因为我无法更新中心下划线(。我当前代码中的所有循环声明都用于该成功的变体,因此我很确定这些不是我的问题。如果您认为它可以帮助您,我也可以提供该代码。我所知道的是,colCnt(列计数(永远在递增,而 undCnt(下划线计数(停留在 2。因此,我怀疑这个 for 循环是我代码中的主要问题,但我不知道在哪里:

// Only print `_` three times as long as there have been 7 total or less vertical lines printed
for (int undCnt = 0; undCnt < 3 && vertCnt <= 6; undCnt++)
{
// Print left and right sections as `_`
if(undCnt != 1)
{
printf("_");
// If printing left section, increment column count
if(undCnt = 1){colCnt++;}
}
// Assign middle section to board array and prints it as `_`
else if(undCnt == 1)
{
arr[rowCnt][colCnt] = '_';
printf("%c", arr[rowCnt][colCnt]);
}
}

法典:

#include <stdio.h>
void PrintBoard(char arr[6][7]);
int main()
{
// Declaration of 7x6 2D board array: board[row][col]
char board[6][7];
PrintBoard(board);
return 0;
}
void PrintBoard(char arr[6][7])
{
int vertCnt = 0; // Counts vertical lines (8 per row, separates sections)
int undCnt = 0; // Counts underscores (3 per section)
int rowCnt = 0; // Counts rows (6 total)
int colCnt = 0; // Count columns (7 total)
// Print game title
printf("      ~~ CONNECT FOUR ~~nn");
for (int rowCnt = 0; rowCnt <= 6; rowCnt++)
{
// If current row is not the first, start it on a new line
if (rowCnt > 0)
{
printf("n");
}
// Creation of row: |___|___|___|___|___|___|___|
for (int vertCnt = 0; vertCnt < 8; vertCnt++)
{
printf("|");
// Only print `_` three times as long as there have been 7 total or less vertical lines printed
for (int undCnt = 0; undCnt < 3 && vertCnt <= 6; undCnt++)
{
// Print left and right sections as `_`
if(undCnt != 1)
{
printf("_");
// If printing left section, increment column count
if(undCnt = 1){colCnt++;}
}
// Assign middle section to board array and prints it as `_`
else if(undCnt == 1)
{
arr[rowCnt][colCnt] = '_';
printf("%c", arr[rowCnt][colCnt]);
}
}
}
}
// Print column numbers
printf("n  1   2   3   4   5   6   7nn");

/* HOW THE BOARD SHOULD LOOK:
~~ CONNECT FOUR ~~             <--- GAME TITLE
|___|___|___|___|___|___|___|
|___|___|___|___|___|___|___|
|___|___|___|___|___|___|___|       <--- BOARD
|___|___|___|___|___|___|___|
|___|___|___|___|___|___|___|
|___|___|___|___|___|___|___|
1   2   3   4   5   6   7         <--- COLUMN NUMBERS
*/
}

如果您有任何问题,请告诉我。谢谢!

您是否考虑过尝试一次打印"___|"?然后您所要做的就是检查列计数,如果它是 0,请打印一个"|",如果它是最大列值,请添加一个换行符。

for(int row_count = 0; row_count<max_rows; rows++)
{
for ( int column_count = 0; column_count<max_columns; columns++)
{
if( column_count==0)
{
printf('|');
}
printf("___|");        
}
printf('n');
}

也许是这样的?

最新更新