2016-07-26 72 views
-12

我知道當你引用一個數組時,它從0開始,但是array.length從0開始還是從1開始?C#沒有array.length從0開始?

因爲如果我指定一個數組大小爲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時,它會給我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; 
    } 
+4

「這是否意味着array.length是0-9?」這個問題沒有意義。長度是單個值,在你的情況下,它將是10. –

+1

你的意思是索引的有效範圍是什麼,答案是'0 .. array.Length - 1'。但'Length'將是您將數組初始化爲非負數的值。 –

+0

所以....很多....空格...請刪除過多的空白空間。 CTRL + K + D! – MichaelThePotato

回答

0

Array.Length指的是數組的大小,即它可以容納多少個元素。索引他們時,這樣的示例迭代會是什麼樣子陣列是基於0 ...

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

如果陣列是空的,它含有0個元素,並且具有長度爲0

如果陣列具有1個元件在0索引,那麼它的長度等於1

如果陣列具有在0 2個元素和1個索引,那麼它的長度等於2.

等等...

+0

這是我想知道的,謝謝! – PeterT

+3

@MKasprzyk - 接受答案不會結束這個問題。 –

+0

@MKasprzyk首先,不要求接受答案。其次,他還不能接受你的答案。 –

-1

我想你的問題是,「爲什麼數組中的最後一個值在索引posPercents.Length - 1而不是posPercents.Length?」

由於數組基於零,所以posPercents.Length = 10,但最後的值不在索引10。它在索引9,因此它的索引是posPercents.Length - 1