我正在编写一个程序,允许用户在计算机上玩游戏连接四。我无法打印出正确的电路板尺寸。我尝试使用嵌套for循环,但输出有点偏。 这是我的代码的一部分:
#include <stdio.h>
#define BOARD_SIZE_VERT 6
#define BOARD_SIZE_HORIZ 7
void display_board(int board[] [BOARD_SIZE_VERT]);
int main ()
{
int board[BOARD_SIZE_HORIZ][BOARD_SIZE_VERT] = {{0}};
display_board(board);
return 0;
}
void display_board(int board[] [BOARD_SIZE_VERT])
{
int i,j;
for (i=0; i<BOARD_SIZE_HORIZ; i++) {
printf ("+---+---+---+---+---+---+---+");
printf ("\n");
for (j=0; j<BOARD_SIZE_VERT; j++)
printf ("| ");
printf("\n");
}
}
这是我的输出:
+---+---+---+---+---+---+---+
| | | | | |
+---+---+---+---+---+---+---+
| | | | | |
+---+---+---+---+---+---+---+
| | | | | |
+---+---+---+---+---+---+---+
| | | | | |
+---+---+---+---+---+---+---+
| | | | | |
+---+---+---+---+---+---+---+
| | | | | |
+---+---+---+---+---+---+---+
| | | | | |
这就是我想要的样子:
+---+---+---+---+---+---+---+
| | | | | | | |
+---+---+---+---+---+---+---+
| | | | | | | |
+---+---+---+---+---+---+---+
| | | | | | | |
+---+---+---+---+---+---+---+
| | | | | | | |
+---+---+---+---+---+---+---+
| | | | | | | |
+---+---+---+---+---+---+---+
| | | | | | | |
+---+---+---+---+---+---+---+
答案 0 :(得分:1)
两个主要问题:您的循环被反转,并且您需要打印一些额外的字符以获得底部和右侧的额外线条。试试这个:
void display_board(int board[] [BOARD_SIZE_HORIZ])
{
int row,col;
for (row=0; row<BOARD_SIZE_VERT; row++) {
printf ("+---+---+---+---+---+---+---+");
printf ("\n");
for (col=0; col<BOARD_SIZE_HORIZ; col++) {
printf ("| ");
}
printf("|\n");
}
printf ("+---+---+---+---+---+---+---+");
}
以下是相关更改:
i
和j
重命名为row
和col
,以便代码更具自我记录性printf("\n")
添加了一个管道,因为您需要一条垂直分隔线而不是每条线的实际插槽数printf("+---....
,因为您需要比实际行数多一个水平分隔符另外,我更改了函数原型中的数组定义,以便第一个索引是行,第二个索引是列。如果您选择这样做,则需要在代码中更改数组的其他用法。例如:
int board[BOARD_SIZE_VERT][BOARD_SIZE_HORIZ] = {{0}};
答案 1 :(得分:1)
void display_board(int board[] [BOARD_SIZE_VERT]){
int i,j;
for (i=0; i<BOARD_SIZE_VERT; i++) {
printf ("+");
for (j=0; j<BOARD_SIZE_HORIZ; j++)
printf("---+");
printf ("\n");
printf ("|");
for (j=0; j<BOARD_SIZE_HORIZ; j++)
printf(" |");
printf ("\n");
}
printf ("+");
for (j=0; j<BOARD_SIZE_HORIZ; j++)
printf("---+");
printf ("\n");
}
答案 2 :(得分:0)
您的代码运行良好。但是你要显示八个"| "
并且你只循环值为6的B OARD_SIZE_VERT
。因此你应该将它增加到8或添加到它。试试这个:
void display_board(int board[] [BOARD_SIZE_VERT]){
int i,j;
for (i=0; i<BOARD_SIZE_HORIZ - 1; i++) {
printf ("+---+---+---+---+---+---+---+");
printf ("\n");
for (j=0; j<BOARD_SIZE_VERT + 2; j++)
printf ("| ");
printf("\n");
}
printf ("+---+---+---+---+---+---+---+\n");
}