我目前正在进行一项练习,要求我生成一个随机数,该随机数可以是 4 个值之一。 (注意我只允许使用 Math.random())
0
1
2
或 3
目前我正在使用这个:randno = (int) (Math.random()*4); // range 0-3
然而,结果必须具有相同的概率。到目前为止,我的测试(尽管缺乏方法)表明 3 的出现次数远远少于其他数字。
这是巧合吗?或者我的生成器的概率不相等。
Thanks!
你的代码运行良好:
public static void main(String[] args) {
int countZero = 0;
int countOne = 0;
int countTwo = 0;
int countThree = 0;
for(int i=0; i<400000; i++){
int randno = (int)(Math.random() * ((3) + 1));
if(randno == 0){
countZero++;
}
else if(randno == 1){
countOne++;
}
else if(randno == 2){
countTwo++;
}
else if(randno == 3){
countThree++;
}
}
System.out.println("Zero: " + countZero);
System.out.println("One: " + countOne);
System.out.println("Two: " + countTwo);
System.out.println("Three: " + countThree);
}
Output:
Zero: 99683
One: 99793
Two: 100386
Three: 100138
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)