你如何制作一个能够在C#中返回数组中元素数量的算法?

时间:2015-04-23 10:25:01

标签: c# arrays algorithm array-algorithms

我已经有一些代码,我认为它正朝着正确的方向发展,但需要帮助填补空白。请注意,我不能在这里使用array.Length,我实际上必须制作一个算法,它将执行与array.Length相同的功能。以下是我到目前为止的情况:

    public static int size(int[] S, int n)
    {
        for (int i = 0; i < n; i++)
        {
            (S[i] 
        }
    }

3 个答案:

答案 0 :(得分:4)

这是一个非常愚蠢的任务,因为C#数组使用Array.Length属性提供它们的长度。我认为你应该在交付时明确这一点。

但是,要遵守规则,请尝试以下方法:

int[] array = new int[10];
int count = 0;

// iterate all elements in the array
foreach(int item in array)
{
    count++;
}

// count will equal 10
return count;

答案 1 :(得分:2)

如果我理解正确,你需要总和,而不是元素的数量,在这种情况下,以下内容就足够了:

public static int size(int[] S, int n)
{
    int sum = 0;
    for (int i = 0; i < n; i++)
    {
        sum += S[i];
    }
    return sum;
}

如果您确实想要数组中的元素数量,请使用:

public static int size(int[] S, int n)
{
    return S.Length;
}

虽然我不明白为什么你需要这个(因为n已经是数组的长度),你可以做到以下几点:

public static int size(int[] S, int n)
{
    int length = 0;
    try
    {
        for (int i = 0; i < n; i++)
        {
            int i2 = S[i];
            length++;
        }
    }
    catch(IndexOutOfRangeException)
    {
    }
    return length;
}

如果仍然无法解答您的问题,请花一些时间以我们能够真正理解您需要的方式重写它。

答案 2 :(得分:0)

我不明白int n的作用;这会有用吗?

    static void Main(string[] args)
    {
        int[] array = new int[] { 3, 4, 5 };
        int count = 0;

        for (int i = 0; i < array.Length; i++)
        {
            count = i + count;
        }
        Console.WriteLine(count);
        Console.ReadKey();
    }
相关问题