How does one compare a char variable to another char variable?
I'm working开发者_开发问答 on a homework assignment in C where we need to make a tic-tac-toe game that can be played between two players. I have all of my code working at this point, except for the function that checks to find a winner. Here's an example of the outcome of a game I tested with:
0 1 2
0 |x|
-----
1 |o|
-----
2 |x|
Congratulations to player 1! You won!
To which I say, no. No, player 1 definitely didn't win. My checks are (forgive me) a series of nested if statements like so:
...
else if (gameboard[0][1] != ' ')
if (gameboard[1][1] == gameboard[0][1])
if(gameboard[2][1] == gameboard[1][1])
return 1;
...
gameboard[0][1] is an 'x'
value, yet the comparison says that gameboard[1][1] is equal to it. Why is this happening and how do I fix it?
Your gameboard might be set up differently from what you are thinking.
#include <stdio.h>
int main()
{
char gameboard[3][3] =
{ {' ', 'x', ' '},
{' ', 'o', ' '},
{' ', 'x', ' '}
};
if (gameboard[0][0] == ' ')
{
printf("0,0 is empty\n");
}
if (gameboard[0][1] != ' ')
{
printf("0,1 has %c\n", gameboard[0][1]);
}
if (gameboard[1][1] == gameboard[0][1])
{
printf("1,1 equals 0,1\n");
}
else
{
printf("1,1 is different from 0,1\n");
}
}
Outputs:
0,0 is empty
0,1 has x
1,1 is different from 0,1
精彩评论