繁体   English   中英

用Java创建单个模具滚动程序,但不是滚动300次,而是滚动320次

[英]Creating a single die roll program in Java, but rather than rolling 300 times, it is rolling 320 times

一段时间以来,我一直在尝试查找该代码中的错误,但我无法弄清。 该程序将一个6面的模具滚动300次,然后输出每个数字被滚动的次数。 但是由于某种原因,它没有滚动300次,而是滚动了320次。 我没有发现for循环有什么问题,所以我真的很茫然。

public static void dieRoll(){
    int[] roll = new int [300];
    int[] count = new int[] {1,2,3,4,5,6};

    for(int i = 1; i<300; i++){
            roll[i] = (int) Math.ceil( (int) (Math.random()*6)+1 );

//          roll[i] = (int) Math.ceil(roll[i]);
//          System.out.println(roll[i]);

            if(roll[i]==1){
                count[0]++;
            }
            else if(roll[i]==2){
                count[1]++;
            }
            else if(roll[i]==3){
                count[2]++;
            }
            else if(roll[i]==4){
                count[3]++;
            }
            else if(roll[i]==5){
                count[4]++;
            }
            else if(roll[i]==6){
                count[5]++;
            }

        //  System.out.println(roll[i]);

    }//i loop   

    System.out.println("The die landed on 1 " + count[0] + " times.");
    System.out.println("The die landed on 2 " + count[1] + " times.");
    System.out.println("The die landed on 3 " + count[2] + " times.");
    System.out.println("The die landed on 4 " + count[3] + " times.");
    System.out.println("The die landed on 5 " + count[4] + " times.");
    System.out.println("The die landed on 6 " + count[5] + " times.");
    System.out.println("The die was rolled this many times: " + (count[0]+count[1]+count[2]+count[3]+count[4]+count[5]));

}//dieRoll()

如果有人可以请我指出错误可能在何处显现,那就太好了。 谢谢。

您像这样初始化计数:

int[] count = new int[] {1,2,3,4,5,6};

现在,1 + 2 + 3 + 4 + 5 + 6等于21。您的循环从1到299,即299次迭代。 当然299 + 21是320

您应该将数组初始化为全零。

最后,您的代码可以简化:

for( int i = 0; i < 300; i++ )
{
    roll[i] = (int) Math.ceil( (int) (Math.random()*6)+1 );
    count[roll[i] - 1]++;
}

暂无
暂无

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

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