【发布时间】:2016-11-09 22:52:46
【问题描述】:
我一直在努力让 headcount 变量是随机的,但无法弄清楚
public class Coin
{
private final int HEADS = 0;
private final int TAILS = 1;
private int face;
private static int seed =0;
private Random r;
public Coin ()
{
r = new Random(seed);
flip();
seed++;
}
public void flip ()
{
face = r.nextInt(2);
}
public int getFace()
{
return face;
}
public void setFace(int newFace)
{
face = newFace;
}
public boolean isHeads ()
{
return (face == HEADS);
}
public String toString()
{
String faceName;
if (face == HEADS)
faceName = "Heads";
else
faceName = "Tails";
return faceName;
}
public static void main(String[] args)
{
Coin myCoin = new Coin();
double randnumber =Math.random();
int headCount=0;
for (int i =1; i<=100; i++)
{
myCoin.flip();
if(myCoin.isHeads())
{
headCount++;
}
}
System.out.println("If I flip my coin 100 times, I get " + headCount + " heads.");
headCount =0;
for (int i =1; i<=100; i++)
{
Coin yourCoin = new Coin();
yourCoin.flip();
if(yourCoin.isHeads())
{
headCount++;
}
}
System.out.println("If I flip 100 coins, I get " + headCount + " tails.");
}
}
每当我编译并运行程序时,我都会得到相同的输出
如果我掷硬币 100 次,我会得到 47 个正面。 如果我掷 100 个硬币,我会得到 50 个反面。
我不明白每次运行程序时如何使 47 和 50 成为新的随机数。我查看了 int Math.Random 和其他随机变量,但不确定如何将其实现到该程序中。
【问题讨论】:
-
嗯,是的,这就是使用种子的全部意义所在:这样您每次都能得到相同的结果。
-
如果您不希望每次都获得相同的结果,请不要每次都使用相同的初始输入为您的随机数生成器播种。设置种子的全部意义在于保证每次运行程序时都得到相同的结果。
-
r = new Random();而不是r = new Random(seed);。 -
@JohnAsle 正如 AzureFrog 所说:“这就是使用种子的全部意义:这样你每次都能得到相同的结果”。