C# int.Parse(string)和#x27;有一些无效的参数。这是什么意思?
我已经试了4个多小时了,我一点也不是专家,我确实需要帮助。知道出了什么问题吗C# int.Parse(string)和#x27;有一些无效的参数。这是什么意思?,c#,parsing,methods,arguments,converter,C#,Parsing,Methods,Arguments,Converter,我已经试了4个多小时了,我一点也不是专家,我确实需要帮助。知道出了什么问题吗 // Declare variables int inches = 0; double centimetres = 0; string input; //Ask for input Console.Write("Enter Number of centimetres to be converted: "); input = Console.ReadLine()
// Declare variables
int inches = 0;
double centimetres = 0;
string input;
//Ask for input
Console.Write("Enter Number of centimetres to be converted: ");
input = Console.ReadLine();
//Convert string to int
centimetres = double.Parse(input);
inches = int.Parse(input);
inches = int.Parse(centimetres / 2.54);
//Output result
Console.WriteLine("Inches = " + inches + "inches.");
}
}转换“英寸=int.Parse(厘米/2.54)代码>毫无意义int.Parse
用于将表示数字的字符串
转换为int
。但是你给它一个双
要使其工作,您的代码需要如下所示:
//Ask for input
Console.Write("Enter Number of centimetres to be converted: ");
double input = Console.ReadLine();
//Convert string to int
double centimetres = double.Parse(input);
double inches = centimetres / 2.54;
//Output result
Console.WriteLine("Inches = " + inches + "inches.");
有几点:
在使用时声明变量,而不是在方法的开头。这是旧语言的遗物,需要首先定义变量
删除inches=int.Parse(输入)代码>完全,因为结果永远不会被使用,因为它在下一行被覆盖
将inches
声明为double
而不是int
。否则,您将无法获得分数英寸
只需将除法结果分配到英寸
。这里不需要解析
厘米/2.54
的结果是双倍的,在中没有过载接受双倍作为参数。问题最像这一行:
英寸=整数(厘米/2.54)
int.Parse接受字符串,厘米/2.54为双精度。要将double转换为int,请使用convert.ToInt32。-1:您不能使用convert.ToInt32将double
转换为字符串。在原始代码中,inches被声明为int,这就是为什么我建议使用接受double并返回int的函数的原因。您说过“要将double转换为字符串,请使用convert.ToInt32”。我现在意识到这可能是一个简单的输入错误,因此如果您更正它,我将删除我的否决票。