首页 > 解决方案 > 程序如何知道数组达到 10?

问题描述

我对这个任务有疑问:

编写一个 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。我们只定义了数组的长度。

标签: c#arrays

解决方案


目前尚不清楚您的问题是什么。既然你完成了作业,你应该至少了解代码是如何工作的。如果您没有编写代码,那么也许您应该询问您复制它的人。如果这不是一个选项,则单步执行/调试代码。

为了解决这个问题,我会略有不同:

您知道长度应该是最大值和最小值之间的差,并且您知道长度多长,所以这应该是简单的算术算法来确定长度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);
    }

推荐阅读