【问题标题】:The best overloaded method match for int.Parse(string)' has some invalid arguments. What does this mean?int.Parse(string)' 的最佳重载方法匹配有一些无效参数。这是什么意思?
【发布时间】:2013-09-30 02:58:45
【问题描述】:

现在已经尝试了 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.");
}

}

【问题讨论】:

    标签: c# parsing methods arguments converter


    【解决方案1】:

    “转换”inches = int.Parse(centimetres / 2.54); 毫无意义。 int.Parse 用于将表示数字的string 转换为int。但是你传递给它一个double。

    要使其正常工作,您的代码需要如下所示:

    //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.");
    

    几点:

    1. 在使用时声明变量,而不是在方法的开头。这是需要首先定义变量的旧语言的遗留问题。
    2. 完全删除inches = int.Parse(input);,因为结果永远不会被使用,因为它会在下一行被覆盖。
    3. 将inches 声明为double 而不是int。否则,您将无法获得小数英寸。
    4. 只需将除法的结果分配给inches。此处无需解析。

    【讨论】:

      【解决方案2】:

      问题最像这行: 英寸 = int.Parse(厘米 / 2.54);

      int.Parse 接受一个字符串,厘米 / 2.54 是一个双精度数。要将 double 转换为 int,请改用 Convert.ToInt32。

      【讨论】:

      • -1:您不能使用Convert.ToInt32 将double 转换为string。
      • 在原始代码中,inches 被声明为 int,这就是为什么我建议使用一个接受 double 并返回 int 的函数。
      • 您说“要将 double 转换为 string 请改用 Convert.ToInt32”。我现在意识到这可能是一个简单的错字,所以如果你更正它,我将删除我的反对票。
      【解决方案3】:

      centimetres / 2.54的结果是double,int.Parse中也没有重载接受double作为参数

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-08
        • 2014-04-10
        • 2015-10-14
        • 2018-07-14
        • 1970-01-01
        • 2013-01-07
        相关资源
        最近更新 更多