for循环不会每次都迭代到所需的数量

for loop will not iterate up to the required number each time

我正在解决一些初学者 Java 问题,这里是我要输出 10 个随机生成的 'coin tosses' 的结果(使用 Math.random()) .

由于某些原因,程序不会一直迭代到10。有时会输出5个结果,或7个,或8个等等

为什么迭代并不总是恒定的?

public class Coin
{
  public static void main(String[] args)
  {
    for (int i=0; i<11; i++)
    {
      if (Math.random() < 0.5)
      {
        System.out.println("H");
      }
      else if (Math.random() > 0.5)
      {
        System.out.println("T");
      }
    }
  }
}

您不需要第二个 if - 目前,在每次迭代中,如果您不打印 "H",您将掷第二个硬币,并且只打印 "T" 如果 第二个硬币 是尾巴。

应该是:

  if (Math.random() < 0.5)
  {
    System.out.println("H");
  }
  else
  {
    System.out.println("T");
  }

使用您的原始代码,第一次出现正面的机会是 50/50,在这种情况下您打印 "H"。如果你 没有 抛出一个 "H" (即其他 50% 的时间),你现在只有 50/50 的机会打印 "T" ,所以您只会看到 "T" 25% 的时间。

所以平均而言,您会看到 7.5 个结果,其中 5 个 "H",2.5 个 "T"。哦,除了你要循环 11 次,所以乘以 1.1

问题出在您每次应该存储结果时都在重新计算随机变量。

您的代码评论:

if (Math.random() < 0.5) { // if the random value is less than 0.5
    System.out.println("H");
} else if (Math.random() > 0.5) { //otherwise, it the new random value is greater than 0.5
    System.out.println("T");
}

这可以通过以下方式更正:

double random = Math.random();
if (random < 0.5) {
    System.out.println("H");
} else { // if it is not "< 0.5", then surely it is "> 0.5" (can't be equal to 0.5)
    System.out.println("T");
}

旁注,您将循环 11 次,而不是 10 次,因为在 0 和 10 之间有 11 个数字。

旁注2:最好不要在这里使用Math.random(),而是使用Random.nextBoolean(),它直接给出一个随机布尔值。

作为 for 循环的第一行,就在第一个 if 之上,输入:

System.out.println("This is iteration #" + i);

所以您真的看到了 "code in motion",并且您可以区分循环实际迭代的次数与循环体的不可预测性,其中输出以伪随机输入为条件。