什么范围的数字?说真的,我头疼试图弄清楚--_-
public function gerRandom(i:uint):uint {
return Math.round(Math.random()*i);
}
Run Code Online (Sandbox Code Playgroud)
从整数0到i其中?我需要这些.一种菜鸟问题,但无论如何:D
Jon*_*org 11
Math.random()将创建一个从0到1的数字(不包括1).因此,您的代码将创建一个介于0和i之间的值,获得0的机会较少,并且i与该范围中的其他值进行比较(它只会在0.5或更小的情况下向下舍入为0,并且在'我'-0.5或更多).
更好的方法是使用
public function getRandom(from:uint, to:uint):uint {
return Math.floor(Math.random()*(to-from+1))+from;
}
Run Code Online (Sandbox Code Playgroud)
(IIRC).
将返回整数0来i,既包容性,但不能以相同的概率.0如果Math.random()*i是间隔[0, 0.5),你会得到的,但1如果它在,你会得到[0.5, 1.5].
请Math.floor(Math.random() * (i + 1))改用.