0

这个程序应该模拟 200 次硬币翻转并打印出最长的正面或反面序列的长度。

大家好,我是编程新手。我被困在写这篇文章的中间。有人可以帮我理解它背后的逻辑吗?任何帮助,将不胜感激。

public class CoinFlips{

  public static void main(String[] args){

    int headsCount=0;
    int tailsCount=0;
    int countTales=0;
    int countHeads=0;

    for (int i=0 ; i<=200; i++){

      double x= Math.random();
      if (x<0.5){
        countTales++;
      }
      else {
        countHeads++;
      }

        //I'm clueless! 
    }

  }

}
4

2 回答 2

0

使用headsCounttailsCount跟踪您的最大值并在序列从头到尾切换时重置计数器,如下所示:

if (x < 0.5) {
   countTales++;
   countHeads = 0; // Reset sequence counter for heads
} else {
   countHeads++;
   countTales = 0; // Reset sequence counter for tails
}

if (countTales > tailsCount) {
   tailsCount = countTales;
}
if (countHeads > headsCount) {
   headsCount = countHeads;
}
于 2014-05-16T02:53:32.740 回答
-1

尝试这个:

public class CoinFlips{

  public static void main(String[] args){

    private int headsCount, tailsCount, countTails, countHeads, maxHeads, maxTails, lastFlip = 0;
    private static final int HEADS = 1;
    private static final int TAILS = 2;

    for (int i=0 ; i<=200; i++){

      double x= Math.random();
      if (x<0.5){
        if (lastFlip == TAILS) {
           tailsCount++;
           if (tailsCount > maxTails) {
              maxTails = tailsCount;
           }
        } else {
          tailsCount = 1;
        }
        lastFlip = TAILS;
        countTails++;
      }
      else {
        if (lastFlip == HEADS) {
           headsCount++;
           if (headsCount > maxHeads) {
              maxHeads = headsCount;
           }
        } else {
          headsCount = 1;
        }
        countHeads++;
      }


    }

    StringBuilder sb = new StringBuilder();
    sb.append("There were ").append(countHeads)
       .append(" heads flipped with the maximum sequential flips of ")
       .append(maxHeads).append(".\n")
       .append("There were ").append(countTails)
       .append(" tails flipped with the maximum sequential flips of ")
       .append(maxTails).append(".\n");
     System.out.print(sb.toString());
  }

}

`

于 2014-05-16T03:04:22.040 回答