函数在C#中传递0,0时返回奇怪的值

huangapple go评论70阅读模式
英文:

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])); 
}

huangapple
  • 本文由 发表于 2023年2月8日 17:43:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75383863.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定