【发布时间】:2019-03-08 12:48:44
【问题描述】:
我在这里是因为我有一个 C 项目,我需要在其中制作井字游戏。
我在这里做的是我问第一个玩家他想在哪里玩,我打印板然后我检查是否有同一玩家的对角线(仅实现 \ 对角线),如果有@ 987654321@ = 真。
问题出在 while 循环中,如果 compteur = 9 或 etat = true 它不会离开循环,我不明白为什么。我试过调试器,这些条件都是真的。
printTab() 是一个简单的 printf 函数
saisieInt() 是一个带有 scanf 和验证数字不是 9
我是猴子吗?
int main()
{
int tab[COTE][COTE] = { 0 };
int compteur = 0,
joueur = 1,
choix;
bool etat=false;
printf("commande : ");
choix = saisieInt();
compteur++;
while ( compteur < 9 || etat != true) {
///position where to place the piece///////////////////////////////
int colonne = choix % 3;
int ligne = choix / 3;
tab[ligne][colonne - 1] = joueur;
///////////////////////////////////////////////
printTab(tab);
///switch between the 2 players///////////////////////////////
if (joueur == 1)
joueur = 2;
else
joueur = 1;
///////////////////////////////////////////////
///check if one has a diagonal line //////////////////////////
if (compteur >= 6) {
int compteurdiag = 0;
for (int i = 0; i < COTE; i++) {
if (tab[i][i] == joueur) {
compteurdiag++;
}
else {
compteurdiag = 0;
}
if (compteurdiag == COTE)
{
etat = true;
}
}
}
///////////////////////////////////////////////
//if (etat == false) {
printf("compteur : %d commande : ", compteur);
choix = saisieInt();
compteur++;
//}
}
printf("compteur : %d termine\n", compteur);
}
void printTab(int t[COTE][COTE]) {
int i, j;
puts("\n|---|---|---|");
for (i = 0; i < COTE; i++) {
for (j = 0; j < COTE; j++) {
printf("|%2d ", t[i][j]);
}
puts("|");
for (j = 0; j < COTE; j++) {
printf("|---");
}
puts("|");
}
}
int saisieInt() {
int valeur, n;
n = scanf("%d", &valeur);
while (n != 1 || valeur > 9) {
printf("Attention, erreur de saisie\nRechoisissez : ");
while (getchar() != '\n');
n = scanf("%d", &valeur);
}
return(valeur);
}
【问题讨论】:
-
这两个测试都必须为 false 才能结束循环。是这样的吗?
-
只需将
tab[ligne][colonne - 1] = joueur;替换为tab[ligne][colonne] = joueur;,看我的回答
标签: c while-loop