有助于将数字转换为符号?

时间:2010-10-23 22:25:10

标签: c++

我希望这段代码代表符号而不是数字(A,O,X)? 有人可以给我一个简单的代码,使数字成为符号吗?谢谢

int game[3][3]; 
int x, y; 
int lines = 0; 

// select a random grid 
srand(time(0)); 
for(x = 0; x < 3; x++) { 
for(y = 0; y < 3; y++) { 
game[x][y] = rand() % 3; 
cout << game[x][y]; 
if (y == 2) 
cout << '\n'; 

} 
} 

for (y = 0; y < 2; y++) 
if (game[0][y] == game[1][y] && game[0][y] == game[2][y]) 
lines++; 

3 个答案:

答案 0 :(得分:2)

您可以使用查找表:

char convert_number_to_letter(unsigned number)
{
    static const char characters[] = "AOX";
    if (number >= sizeof(characters) - 1)
        return '\0'; // or other error handling
    return characters[number];
}

答案 1 :(得分:1)

chat c;
switch(game[x][y])
{
   case 0:
      c = 'A';
      break;
   case 1:
      c = 'O';
      break;
   case 2:
      c = 'X';
      break;
}

char c;
if(game[x][y] == 0)
    c = 'A';
else if(game[x][y] == 1)
   c = 'O';
else 
   c = 'X';

答案 2 :(得分:1)

使用另一个数组,填充所需的字符值,然后使用生成的随机数索引该数组:

char chars[] = { 'A', 'O', 'X' };
... 
for(x = 0; x < 3; x++) { 
  for(y = 0; y < 3; y++) { 
    game[x][y] = chars[rand() % 3];
    ...
  } 
}