簡體   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