C#控制台扫雷开发:int转char返回表情/空而非数字0-3问题求助
C#控制台扫雷游戏数字转字符问题
我正在学习C#,尝试开发一款控制台简易扫雷游戏。在实现统计指定坐标周围地雷数量的howManyMinesHaveBeenPut方法时,将地雷数字(int/short类型)转换为char返回时,未得到预期的数字0-3,反而返回空或表情符号。我尝试过强制类型转换、Convert.ToChar以及切换int和short类型,但问题仍未解决。
相关代码
public char howManyMinesHaveBeenPut(int xCoordinate, int yCoordinate) { short howMany = 0; if(canPlayerPut(xCoordinate - 1, yCoordinate - 1) && isMine(xCoordinate - 1, yCoordinate - 1)) { howMany++; Console.WriteLine("Mina 1"); } if (canPlayerPut(xCoordinate, yCoordinate - 1) && isMine(xCoordinate, yCoordinate - 1)) { howMany++; Console.WriteLine("Mina 2"); } if (canPlayerPut(xCoordinate + 1, yCoordinate - 1) && isMine(xCoordinate + 1, yCoordinate - 1)) { howMany++; Console.WriteLine("Mina 3"); } if (canPlayerPut(xCoordinate - 1, yCoordinate) && isMine(xCoordinate - 1, yCoordinate)) { howMany++; Console.WriteLine("Mina 4"); } if (canPlayerPut(xCoordinate + 1, yCoordinate) && isMine(xCoordinate + 1, yCoordinate)) { howMany++; Console.WriteLine("Mina 5"); } if (canPlayerPut(xCoordinate - 1, yCoordinate + 1) && isMine(xCoordinate - 1, yCoordinate + 1)) { howMany++; Console.WriteLine("Mina 6"); } if (canPlayerPut(xCoordinate, yCoordinate + 1) && isMine(xCoordinate, yCoordinate + 1)) { howMany++; Console.WriteLine("Mina 7"); } if (canPlayerPut(xCoordinate + 1, yCoordinate + 1) && isMine(xCoordinate + 1, yCoordinate + 1)) { howMany++; Console.WriteLine("Mina 8"); } return Convert.ToChar(howMany); }
问题原因与解决方法
问题核心是数字到字符的转换逻辑错误:直接调用Convert.ToChar(howMany)时,程序会把数字当作Unicode编码值来转换。比如数字0对应Unicode的空字符\0,数字1对应不可见的控制字符,这些自然不是你需要的'0'、'1'等字符。
正确的转换方式有两种:
- 利用ASCII码偏移:字符'0'的ASCII码是48,给数字加上'0'(本质是加48)再转成char:
return (char)(howMany + '0'); - 先把数字转成字符串,再取第一个字符:
return howMany.ToString()[0];
两种方式都能得到你预期的字符'0'、'1'、'2'等。
内容的提问来源于stack exchange,提问作者user19845858
相关产品推荐
相关产品推荐

