【问题标题】:C# does array.length start from 0?C# array.length 是否从 0 开始?
【发布时间】:2016-07-26 12:31:08
【问题描述】:

我知道当你引用一个数组时,它从 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(我 +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 年过去了,我对这个问题感到非常尴尬,但这是一个很好的进步参考点

【问题讨论】:

  • "这是否意味着 array.length 为 0-9?"这个问题没有意义。长度为单个值,在您的情况下为 10。
  • 你的意思是什么是有效的索引范围,答案是0 .. array.Length - 1。但是Length 将是您将数组初始化为的任何非负值。
  • SO.... MUCH.... SPACING... 请删除过多的空格。 CTRL+K+D!
  • 对于随机槽,您可以简单地使用myArray[myRandom.Next(myArray.Length)]
  • @HenkHolterman 完美解决了我的问题,谢谢!

标签: c# arrays


【解决方案1】:

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

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

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

等等……

【讨论】:

  • @MKasprzyk -- 接受答案不会关闭问题。
  • @MKasprzyk 首先,不要乞求接受答案。其次,他还不能接受你的回答。
  • @royap - 好的,我明白了,但这是给出正确答案的标志。我说的对吗?
  • 谁说你是对的?谁说别人的答案不好? @MKasprzyk
  • @PatrickHofman OP 说它在第一条评论中是正确的,你不应该仅仅因为有人在某个时候可能会想到一个更好的答案就留下一个未回答的问题,尽管我同意纠缠 OP在他们准备好之前标记答案也不是一个好主意
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-04-21
      • 1970-01-01
      • 2019-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 2012-01-07
      相关资源
      最近更新 更多