我正在尝试学习 C 语言,在这里我需要一些帮助。
我正在尝试为井字游戏制作程序。我尝试在 main 函数中执行它的第一部分,但它不起作用。但是,当我使用另一个功能时,它起作用了。它是如何以及为什么起作用的?(这两个程序都附在下面)。
另外,我在带有“square 1”和“square 2”的scanf中使用了“%s”而不是“%c”。为什么“%c”在这里不能正常工作?
在此先感谢您的帮助。
// first program
#include <stdio.h>
int main ()
{
int player;
char square1;
char square2;
char Nesta[9]={'1','2','3','4','5','6','7','8','9'};
int player1;
int player2;
printf("choose one for x or two for o\n");
scanf("%i", &player);
if (player==1)
{
player1='x';
player2='o';
}
else
{
player1 ='o';
player2='x';
}
printf(
"1 + 2 + 3 \n"
"---+----+-----\n"
"4 + 5 + 6 \n"
"---+----+-----\n"
"7 + 8 + 9 \n"
);
for (int i=0; i<3; ++i)
{
printf("please enter the number of the sqaure ");
scanf("%s",&square1 );
printf("please enter the number of the sqaure ");
scanf("%s",&square2 );
for (int j=0; j<9; ++j)
{
if (square1 == Nesta[j])
{
Nesta[j]=player1;
printf(
"%c + %c + %c \n"
"----+-----+--- \n"
"%c + %c + %c \n"
"----+-----+--- \n"
"%c + %c + %c \n", Nesta[0],Nesta[1], Nesta[2], Nesta[3],Nesta[4],Nesta[5],Nesta[6],Nesta[7],Nesta[8]);
}
}
for (int k=0; k<9; ++k)
{
if (square2 == Nesta[k])
{
Nesta[k]=player2;
printf(
"%c + %c + %c \n"
"----+-----+--- \n"
"%c + %c + %c \n"
"----+-----+--- \n"
"%c + %c + %c \n", Nesta[0],Nesta[1], Nesta[2], Nesta[3],Nesta[4],
Nesta[5],Nesta[6],Nesta[7],Nesta[8]);
}
}
}
return 0;
}
使用 gamecont 功能时它工作得很好!
// the second program
#include <stdio.h>
char Nesta[9]={'1','2','3','4','5','6','7','8','9'};
int player1;
int player2;
int gamecont ()
{
char square2;
printf("please enter the number of the square ");
scanf("%s",&square2 );
for (int j=0; j<9; ++j)
if (square2 == Nesta[j])
{
Nesta[j]=player2;
printf(
"%c + %c + %c \n"
"----+-----+--- \n"
"%c + %c + %c \n"
"----+-----+--- \n"
"%c + %c + %c \n", Nesta[0],Nesta[1], Nesta[2], Nesta[3],Nesta[4],
Nesta[5],Nesta[6],Nesta[7],Nesta[8]);
}
}
int main ()
{
int player;
char square1;
printf("choose one for x or two for o\n");
scanf("%i", &player);
if (player==1)
{
player1='x';
player2='o';
}
else
{
player1 ='o';
player2='x';
}
printf(
"1 + 2 + 3 \n"
"---+----+-----\n"
"4 + 5 + 6 \n"
"---+----+-----\n"
"7 + 8 + 9 \n"
);
for (int i=0; i<3; ++i)
{
printf("please enter the number of the square ");
scanf("%s",&square1 );
for (int j=0; j<9; ++j)
{
if (square1 == Nesta[j])
{
Nesta[j]=player1;
printf(
"%c + %c + %c \n"
"----+-----+--- \n"
"%c + %c + %c \n"
"----+-----+--- \n"
"%c + %c + %c \n", Nesta[0],Nesta[1], Nesta[2], Nesta[3],Nesta[4],Nesta[5],Nesta[6],Nesta[7],Nesta[8]);
gamecont() ;
}
}
}
return 0;
}