【问题标题】:In C# How to correctly pass an int array to a function在 C# 中如何正确地将 int 数组传递给函数
【发布时间】:2022-01-06 11:51:42
【问题描述】:

如何将具有未知数量整数的数组传递给函数? 谁能告诉我我做错了什么?

尝试运行代码时出现以下错误:

错误 CS1501 方法“解决方案”没有重载需要 6 个参数

using System;

namespace IntegerTest
{
    class Program
    {
        public static int Solution(int[] input)
        {
            Array.Sort(input);

            int index = 0;

            // Skip negatives
            while (index < input.Length && input[index] < 1)
                index++;

            int expected = 1;
            while (index < input.Length)
            {
                if (input[index] > expected)
                    return expected;

                // Skip number and all duplicates
                while (index < input.Length && input[index] == expected)
                    index++;

                expected++;
            }

            return expected;
        }

        public static void Main()
        {
            Console.WriteLine(Solution( 1, 3, 6, 4, 1, 2));

        }
    }

}
    

【问题讨论】:

标签: c# arrays


【解决方案1】:

您可以使用数组参数调用函数(例如Solution(new[] {1, 3, 6, 4, 1, 2}),或修改函数签名以采用params 参数(int Solution(params int[] input))。

【讨论】:

    【解决方案2】:

    你的方法接受int[],所以创建一个new int[]

    Solution(new int[] {1, 3, 6, 4, 1, 2});
    

    【讨论】:

      【解决方案3】:

      您将 6 个参数传递给一个接受一个的方法。将您的主要方法更改为以下内容:

          public static void Main()
          {
              int[] arr = { 1, 3, 6, 4, 1, 2};
              Console.WriteLine(Solution(arr));
      
          }
      

      【讨论】:

        猜你喜欢
        • 2021-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-28
        • 2019-11-05
        • 2011-12-05
        相关资源
        最近更新 更多