C#的array.length从0开始

本文关键字:开始 length array | 更新日期: 2023-09-27 17:58:36

我知道当你引用一个数组时,它从0开始,但array.length是从0开始还是从1开始?

因为如果我指定一个数组大小为10,我引用它0-9,这是否意味着array.length是0-9?

我这么问是因为我使用array.length作为随机生成的数字的最大大小,但我这样做就像

randomArrayPointer = randomIntNum( 0 , ( posPercents.Length - 1 ) ); //generates a random number that fits the arrays range
if( randomArrayPointer < posPercents.Length ) //ensures the integer is less than the length of the array
{
    return ( posPercents [ randomArrayPointer ] );
}
else
{
    return ( posPercents [ 0 ] );
}

这是我的方法randomIntNumber(I+1到最大值,因为当指定1到10作为Random()的输入时,它会给我一个介于0-9之间的数字)

public static int randomIntNum( int min , int max )
{
    if( max != 1 & ( max != ( min + 1 ) ) ) //if max isn't 1 and max isn't the minimum + 1
    {
        max = max - 1; //remove 1, this corrects the random generator so that the parameters sent don't need adjusting
    }
    int newInt;
    newInt =  rnd.Next( min , max );
    return ( newInt );
}

编辑:

这是我现在的方法,谢谢大家。

    public static double randomPercentChange( Boolean? positive )
    {
        if( positive == true )
        {
            return ( posPercents [ rnd.Next( posPercents.Length ) ] );
        }
        else if( positive == false )
        {
            return ( negPercents [ rnd.Next( negPercents.Length ) ] );
        }
        else if( positive == null )
        {
            return ( 1 );
        }
        return 1;
    }

编辑2:4年过去了,我对这个问题感到非常尴尬,但它是进步的一个很好的参考点

C#的array.length从0开始

如果数组为空,则它包含0个元素,长度为0。

如果数组在0索引中有1个元素,则其长度等于1。

如果数组在0和1索引中有2个元素,则其长度等于2。

等等…

数组。长度是指数组的大小,即它可以容纳多少个元素。数组在索引时是基于0的,因此示例迭代看起来像。。。

for(var i = 0; i < myArray.Length; i++)
{
   var elm = myArray[i];
   //do something with the element
}

我想你的问题是,"为什么数组中的最后一个值在索引posPercents.Length - 1而不是posPercents.Length?"

由于数组是从零开始的,posPercents.Length = 10,但最后一个值不在索引10处。它的索引为9,因此它的索引是posPercents.Length - 1