该程序应该模拟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!
}
}
}
答案 0 :(得分:0)
使用headsCount
和tailsCount
跟踪您的最大值,并在序列从头到尾切换时重置计数器,如下所示:
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;
}
答案 1 :(得分:-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());
}
}
`