程序如何知道阵列达到10?

时间:2018-06-11 18:28:32

标签: c# arrays

我对此任务有疑问:

  

编写一个C#程序,它将接受一个整数列表并检查如何   需要很多整数来完成范围。例如[1,3,4,   7,9],1-9之间 - >列表中不存在2,5,6,8。所以   输出将为4.

以下是该任务的代码:

public class Example
{
    public static int consecutive_array(int[] input_Array)
    {
        Array.Sort(input_Array);
        int ctr = 0;
        for (int i = 0; i < input_Array.Length - 1; i++)
        {
            ctr += input_Array[i + 1] - input_Array[i] - 1;
        }
        return ctr;
    }

    public static void Main()
    {
        Console.WriteLine(consecutive_array(new int[] { 1, 3, 5, 6, 9 }));
        Console.WriteLine(consecutive_array(new int[] { 0, 10 }));
        Console.ReadLine();
    }
}

我的问题是,程序如何知道数组从0到9.我们只定义了数组的长度。

2 个答案:

答案 0 :(得分:1)

不清楚你的问题是什么。由于您完成了作业,因此您应该至少了解代码的工作原理。如果你没有编写代码,那么也许你应该问你复制它的人。如果这不是一个选项,那么逐步/调试代码。

要解决这个问题,我的做法略有不同:

你知道长度应该是max&amp;和最小值,你知道长度是多长,所以这应该是简单的算术算法,以确定input_Array的长度与的长度之间的差异如果它是顺序满的话:

    public static int consecutive_array(int[] input_Array)
    {
        // we know the array length SHOULD be ==( max - min + 1)
        Array.Sort(input_Array);
        int fullLength = (input_Array[input_Array.Count()-1] - input_Array[0] + 1);
        return (fullLength - input_Array.Length);
    }

答案 1 :(得分:-1)

您从数组的长度中减去1并使用小于运算符。这将在结束前有效地将其切断1个项目。