我正在尝试使用下面的代码来模拟抛硬币。
public class Coin
{
public static double result;
int[] count = new count[2];
public static void flip()
{
result = Math.random();
}
public static boolean isHeads()
{
if (result == 0.0)
{
count[0]++;
return false;
}
else
{
count[1]++;
return true;
}
}
public static void main(String[] args)
{
flip();
isHeads();
System.out.println(count[0]);
System.out.println(count[1]);
}
}
由于某种原因 Eclipse 说
导入java.util.Random;
从未被使用过,尽管我明显在使用它。我没有将 for 循环放入上面的代码中,但它循环了 n 次,然后输出结果。无论循环多少次,它总是返回结果大于 0.0,这是不正确的。我是否错误地调用了 Math.random?
最佳答案
您正在使用 Math,它可能正在使用 Random,但您没有在任何地方使用 Random。
No matter how many times it loops it always returns that the result is greater than 0.0 which can't be right. Am I calling Math.random incorrectly?
0.0 到 1.0 之间有 2 ^ 53 个可能的值,并且由于 Random 仅使用 48 位种子,因此您可能会生成它将创建的每个 double
并且不会出现任何值。如果您使用 SecureRandom,您有二分之一^ 53 的机会返回 0.0。
关于java - math.Random 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12533668/