所以我提早提出了我的问题,以为我一切都很好,但是我搞砸了,意识到我完全理解了这个问题。
我不需要计算超过1000个骰子骰子的蛇眼平均数,但不需要计算超过1000次骰子的蛇眼的骰子平均数。
我对如何做到这一点有些迷茫。
我尝试了这个:
public class RollDiceforloop {
public static void main(String[] args) {
int die1, die2, snakeye, rolls, game;
snakeye = 0;
die1 = 0;
die2 = 0;
rolls = 0;
for (game = 0; game < 1000; game++) {
die1 = (int)(Math.random()*6)+1;
die2 = (int)(Math.random()*6)+1;
if (die1 != 1 && die2 != 1); {
rolls +=1;
}
if (die1 == 1 && die2 == 1) {
snakeye +=1;
rolls +=1;
}
}
float average = snakeye / (float) rolls;
TextIO.putln(""+snakeye+" Snake Eyes over "+game+" games, with an average of "+average+" rolls required to get a Snake Eye.");
}
}
但是我没有得到正确的结果。我对如何做到这一点有些迷茫。请帮助?
最佳答案
您的逻辑有些错误。您需要进行N次测试(游戏),每项测试都必须等到出现蛇眼并计算必要的掷骰次数。您可能会说您需要等待,直到没有蛇眼出现。要计算平均值,您需要存储每个测试的结果。
例:
public static void main( String[] args )
{
int dice1;
int dice2;
// The amount of tests
final int SIZE = 10000000;
// store all results we got from a single test
int[] result = new int[SIZE];
// loop through the tests
for(int i = 0; i < SIZE;i++)
{
// initialize counter for every test
int rolls = 0;
do
{
// roll counter increases
rolls++;
dice1 = (int)(Math.random()*6)+1;
dice2 = (int)(Math.random()*6)+1;
// check if condition is met.
}while(dice1 != 1 || dice2 != 1);
// store the result of the test
result[i] = rolls;
}
// calculate the average amount of rolls necessary
double avg = Arrays.stream( result ).sum() / (double)SIZE;
System.out.println( avg );
}
关于java - 对于循环,运行程序1000次,则在JAVA中获得蛇眼所需的平均滚动数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49996353/