您的代码存在问题:
您对二维数组的声明是错误的。第一个括号应该包含行数和第二个括号 - 列数。(你在你的代码中倒退了)
而不是这样做board[ rows ][ columns * 2 ] = '|';
..将循环计数器增加2要简单得多(请参阅我的代码)
要打印一个字符,你选择%c
不是描述符%d
最后不是一个大问题,但在 main 中返回是一个好习惯
抱歉,您的代码存在另一个大问题。您将 drawBoard 函数声明为char
.. 但您没有char
从中返回任何内容..(如果您打开 -Wall 标志,您的编译器会抱怨).. 将其更改void
为
这是固定代码:(请参阅代码中的注释以了解您的代码的问题)
另外现在我正在用'X'填充数组..你可以改变它以满足你的需要
#include <stdio.h>
void drawBoard()
{
char board[3][7], XO; // you were declaring your array wrong .. it rows in first bracket and columns in 2nd bracket
int rows, columns;
for ( rows = 0 ; rows < 3 ; rows++ ){
for ( columns = 0 ; columns < 7 ; columns=columns+2 ){ // to fill every second elemnt of the array .. just increment the counter by 2
board[ rows ][ columns ] = '|';
}
}
for ( rows = 0 ; rows < 3 ; rows++ ){
for ( columns = 1 ; columns < 7 ; columns = columns+2 ){
board[ rows ][ columns ] = 'X';
}
}
for ( rows = 0 ; rows < 3 ; rows++ )
{
for ( columns = 0 ; columns < 7 ; columns++ )
{
printf( "%c", board[rows][columns] ); // its supposed to be %c as you are printing a character
}
printf("\n");
}
}/* end function drawboard */
int main()
{
drawBoard();
return 0;
}
输出;
Sukhvir@Sukhvir-PC ~
$ gcc -Werror -g -o test test.c
Sukhvir@Sukhvir-PC ~
$ ./test
|X|X|X|
|X|X|X|
|X|X|X|
-------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- --------------
我对游戏的解释:(根据 Maxime 的建议稍作编辑)
#include <stdio.h>
void drawBoard(char board[][3])
{
int rows, columns;
for ( rows = 0 ; rows < 3 ; rows++ )
{
for ( columns = 0 ; columns < 3 ; columns++ )
{
if(board[rows][columns]){
printf( "|%c", board[rows][columns] );
}else{
printf("| ");
}
}
printf("|\n");
}
}/* end function drawboard */
int main()
{
char game[3][3]={{0}};
int totalEntry =0,row,column;
char value;
while(totalEntry<=9){
printf("Enter (x) or (o): ");
scanf("%c",&value);
getchar();
printf("Enter row number: ");
scanf("%d",&row);
getchar();
printf("Enter Column number: ");
scanf("%d",&column);
getchar();
game[row][column] = value;
drawBoard(game);
}
return 0;
}
输出:(停下来保持简短..但你明白了)
$ ./test
Enter (X) or (O): x
Enter row number: 0
Enter Column number: 0
|x| | |
| | | |
| | | |
Enter (X) or (O): o
Enter row number: 1
Enter Column number: 1
|x| | |
| |o| |
| | | |
Enter (X) or (O): x
Enter row number: 2
Enter Column number: 2
|x| | |
| |o| |
| | |x|
Enter (X) or (O):
[4]+ Stopped