C# int.Parse(string)和#x27;有一些无效的参数。这是什么意思?

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()

我已经试了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();

    //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”。我现在意识到这可能是一个简单的输入错误,因此如果您更正它,我将删除我的否决票。