所以现在我编辑了代码,当有四个头时,计算一行中的头数,当有五个头时计算一行的头数。我有以下正确运行的代码,但它只计算四个数字,而不是五个数字。有人能帮我吗?我将跟踪运行时得到的结果复制并粘贴到我的代码之后。
public class Flip {
public static void main(String[] args)
{
final int FLIPS = 100;
int heads = 0;
int consecCountfour = 0;
int consecCountfive = 0;
System.out.println("Trail Tosses:");
for (int i = 1; i<= FLIPS; i++)
{
if (Math.random() < 0.5) {
System.out.print("h");
heads++;
}
else {
System.out.print("t");
if (heads == 4) { consecCountfour++; }
heads = 0;
if (heads == 5) { consecCountfive++; }
heads = 0;
}
}
System.out.println("n");
System.out.print("Count hhhh:"+ consecCountfour);
System.out.print(" Count hhhhh:" + consecCountfive);
}
}
一个不错的解决方案是计算翻转尾部时设置为0的连续头部的数量。
final int FLIPS = 100;
int heads = 0;
int consecCount = 0;
for (int i = 1; i<= FLIPS; i++)
{
if (Math.random() < 0.5) {
System.out.print("h");
heads++;
}
else {
System.out.print("t");
if (heads == 4 || heads == 5) { consecCount++; }
heads = 0;
}
}
System.out.print(consecCount);