英文:
Function returns strange value when passed 0,0 on c#
问题
我一直在尝试编写战舰游戏的代码,作为大学作业的一部分,但在测试时遇到了一个奇怪的问题。当我传递0,0作为坐标时,坐标1 以某种原因返回48。有人能提供一些帮助吗?
public static int[] getYXCoordinate(string coordinate)
{
return new int[2] { (int)coordinate[2], (int)coordinate[0] };
}
值得注意的是,在传递任何参数之前,它们都被验证为x,y的形式。
英文:
Ive been trying to code battleships as part of a college assignment but I'm running into a strange issue whilst testing. When I pass 0,0 as the coordinate, coordinate1 returns 48 for some reason. Could anyone offer some help?
public static int[] getYXCoordinate(string coordinate)
{
return new int[2] ((int)coordinate[2],(int)coordinate[0]);
}
For the record, before any arguments are passed, they are validated to be in the form x,y.
答案1
得分: 1
它返回48
,因为它返回char
本身。如果你查看ASCII表,你会看到字符0
以DEC表示为48
。
另外,你可以考虑使用System.Drawing
中的Point
结构。
public static Point GetYXCoordinateFromString(string coordinate)
{
//将字符串以','字符拆分
//如果字符串中没有至少一个',',将会抛出异常
var str = coordinate.Split(',');
//将两个部分解析为整数,并创建一个新的Point()结构
//如果在以','分隔的第一个或第二个部分中有整数以外的字符,将会抛出异常
return new Point(int.Parse(str[0]), int.Parse(str[1]);
}
英文:
It returns 48
because you are returning the char
itself. If you take a look into the ASCII Table you see that the character 0
is represented as 48
in DEC
Also you may consider using the Point
struct from System.Drawing
public static Point GetYXCoordinateFromString(string coordinate)
{
//Splits the string at the ',' character
//Will throw if there is not at least one ',' in the string
var str = coordinate.Split(',');
//Parses the two parts to ints and creates a new Point() struct out of it
//Will throw if there are other chars then integers within the first or second part seperated by ','
return new Point(int.Parse(str[0]), int.Parse(str[1]));
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论