繁体   English   中英

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

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

我只是在解决一些Java初学者问题,在这里我要输出10个随机生成的“抛硬币”的结果(使用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 (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之间(含10和10),包含11个数字。

旁注2:最好不要在此处使用Math.random() ,而应使用Random.nextBoolean() ,它直接给出随机的布尔值。

如果不需要, 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

作为for循环的第一行,在if的第一行上方,放置:

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

因此,您确实看到了“运动中的代码”,并且可以区分循环实际迭代的次数与循环主体的不可预测的本质,在这种情况下,输出取决于伪随机输入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM