【问题标题】:Creating a single die roll program in Java, but rather than rolling 300 times, it is rolling 320 times在 Java 中创建单个掷骰子程序,但不是滚动 300 次,而是滚动 320 次
【发布时间】:2015-07-06 12:13:12
【问题描述】:

一段时间以来,我一直试图找出错误在此代码中的位置,但我就是想不通。该程序正在滚动一个 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()

如果有人能指出错误可能在哪里表现出来,那就太棒了。谢谢。

【问题讨论】:

  • 如果您在进入循环之前 执行最后一次 println,您将看到问题所在。您的 count 数组以非零值开头。

标签: java dice


【解决方案1】:

你这样初始化你的计数:

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]++;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    • 2013-05-09
    • 1970-01-01
    • 2018-09-06
    • 1970-01-01
    • 2018-12-17
    • 2021-05-16
    相关资源
    最近更新 更多