我正在尝试使用下面的代码模拟硬币翻转.
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]);
}
}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,Eclipse说的是
import java.util.Random;
即使我明显使用它也从未使用过.我没有把我的for循环放到上面的代码中但它循环了很多次然后输出结果.无论它循环多少次,它总是返回结果大于0.0,这是不对的.我是否错误地调用了Math.random?
您正在使用Math,它可能正在使用Random,但您没有在任何地方使用Random.
无论它循环多少次,它总是返回结果大于0.0,这是不对的.我是否错误地调用了Math.random?
在0.0和1.0之间有2 ^ 53个可能的值,并且由于Random仅使用48位种子,因此您可以生成double
它将创建的每个值,并且不会发生任何一个值.如果你使用SecureRandom,你有一个2 ^ 53的机会返回0.0.
我建议使用
java.util.Random
public static void main(String[] args) throws Exception {
Random rand = new Random();
int headCount = 0;
int tailCount = 0;
for (int i = 0; i < 10; i++) {
int value = rand.nextInt(2);
if (value == 0) {
System.out.println("Heads");
headCount++;
} else {
System.out.println("Tails");
tailCount++;
}
}
System.out.println("Head Count: " + headCount);
System.out.println("Tail Count: " + tailCount);
}
Run Code Online (Sandbox Code Playgroud)