我想要一个随机数生成器来模拟抛硬币,这就是我所做的
public class CoinToss
{
public static void main(String args[])
{
int num=(int)(1000*Math.random());
if(num<500)
System.out.println("H");
else
System.out.println("T");
}
}
结果令人沮丧,因为我在 20 次运行中得到了 16 个正面和 4 个反面。 这似乎不是随机的。这是可能的,但我想要一个总体意见,该程序是否正确?我在数学上遗漏了一些东西吗?
最佳答案
稍微修改一下你的代码,它似乎足够随机。
代码:
int h = 0;
int t = 0;
for (int i = 0; i < 1000; i++) {
int num = (int) (1000 * Math.random());
if (num < 500) {
h++;
} else {
t++;
}
}
System.out.println("T:" + t);
System.out.println("H:" + h);
输出:
T:506
H:494
我想这就是随机性吧^^
关于java - 使用随机数的硬币抛掷看起来并不完全随机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36937550/