【发布时间】: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 完美解决了我的问题,谢谢!