我在试着学习C语言 我需要一些帮助
我正在尝试制作一个 tic-tac-toe 游戏的程序。 我尝试在主函数中做第一点, 但是它没有起作用。 但是, 当我使用另一个函数时, 它就起作用了。 它是如何和为什么起作用的? (两个程序都附在下面) 。
Also, I used "%s" instead of "%c" in scanf with "square 1" and "square 2". Why doesn t "%c" work fine in here ?
提前感谢您的帮助。
// 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
");
scanf("%i", &player);
if (player==1)
{
player1= x ;
player2= o ;
}
else
{
player1 = o ;
player2= x ;
}
printf(
"1 + 2 + 3
"
"---+----+-----
"
"4 + 5 + 6
"
"---+----+-----
"
"7 + 8 + 9
"
);
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
"
"----+-----+---
"
"%c + %c + %c
"
"----+-----+---
"
"%c + %c + %c
", 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
"
"----+-----+---
"
"%c + %c + %c
"
"----+-----+---
"
"%c + %c + %c
", 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
"
"----+-----+---
"
"%c + %c + %c
"
"----+-----+---
"
"%c + %c + %c
", 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
");
scanf("%i", &player);
if (player==1)
{
player1= x ;
player2= o ;
}
else
{
player1 = o ;
player2= x ;
}
printf(
"1 + 2 + 3
"
"---+----+-----
"
"4 + 5 + 6
"
"---+----+-----
"
"7 + 8 + 9
"
);
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
"
"----+-----+---
"
"%c + %c + %c
"
"----+-----+---
"
"%c + %c + %c
", Nesta[0],Nesta[1], Nesta[2], Nesta[3],Nesta[4],Nesta[5],Nesta[6],Nesta[7],Nesta[8]);
gamecont() ;
}
}
}
return 0;
}