将人的高度从英尺和英寸转换为英寸c#
本文关键字:转换 高度 | 更新日期: 2023-09-27 18:10:00
我使用一个外部API请求一个人的身高英寸,所以5.10"(5英尺和10英寸)将是70",现在我想给用户一个输入框,这样他们就可以输入5.10,然后将其转换为70,以便将其传递给API。我认为有一个直接的解决方案,那就是:
- 截断输入到0
- 从英尺转换为英寸
- 得到尾号
- 转换为int
- 添加
但我认为这可能不是那么简单,请给我指出正确的方向。编码它应该不会对输入的细节和验证造成任何问题,例如,如果用户键入5.12或5.13(例如
也许这样做会有所帮助:
// assuming we have string inputStr
string[] tokens = inputStr.Split ('.');
if (tokens.Length < 2 || tokens.Length > 2)
{
throw new ArgumentException ();
}
int feet = int.Parse (tokens[0]);
int inches = int.Parse (tokens[1]);
if (inches >= 12)
{
throw new ArgumentException ();
}
int totalInches = (feet * 12) + inches;
这应该工作,没有测试它。您还需要添加错误处理。
所以如果用户输入5。10、您可以像这样解析它以获得英尺和英寸:
string userInput = "5. 10";
int feet = Convert.ToInt32(userInput.Substring(0, userInput.IndexOf(".")));
int inches = Convert.ToInt32(userInput.Substring(userInput.IndexOf(".") + 1).Trim())
然后计算
return (feet * 12) + inches;
显然,您需要进行大量的错误处理,以确保用户输入的格式正确。
你可以试试:
private int toInches(string input)
{
if (input.Contains("."))
{
string sfeet = input.Split('.')[0];
string sinches = input.Split('.')[1];
int feet, inches;
if (int.TryParse(sfeet, out feet) && int.TryParse(sinches, out inches))
{
return feet*12 + inches;
}
throw new Exception("The input is invalid");
}
else
{
int output;
if (int.TryParse(input, out output))
{
return output*12;
}
throw new Exception("The input is invalid");
}
}