gpt4 book ai didi

java - 在 Java 中创建一个单次掷骰子程序,但不是掷骰子 300 次,而是掷骰子 320 次

转载 作者:行者123 更新时间:2023-11-29 09:40:41 24 4
gpt4 key购买 nike

一段时间以来,我一直试图找出这段代码中的错误所在,但我就是想不出来。该程序将 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]++;
}

关于java - 在 Java 中创建一个单次掷骰子程序,但不是掷骰子 300 次,而是掷骰子 320 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31237305/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com