gpt4 book ai didi

Java掷骰子游戏While循环随机数生成

转载 作者:行者123 更新时间:2023-11-30 04:02:43 24 4
gpt4 key购买 nike

好吧,我正在尝试创建一个骰子游戏,其中 args[0] 是玩游戏的次数。游戏.... 掷两个骰子,如果总和不等于 7,则将其值添加到总和中。如果总和等于 7,则游戏结束。我想跟踪所有游戏中最大的总和和最小的总和,该总和应该始终为零,因为当总和等于 7 时,它会将总和设置为 0。这是我的代码。我不认为它打印的内容是我想要的...帮助?另外我如何在 Eclipse 中自动格式化?

public class diceGame {
public static void main(String[] args) {
int dice1;
int dice2;
int count=0;
int theSum=0;
int lowest=500;
int finalSum=0;
int diceSum=0;
while (count !=Integer.parseInt(args[0])){
count=count+1;
theSum=0;
while(diceSum!=7){
diceSum=0;
dice1=1 + (int)(Math.random() * ((6 - 1) + 1));
dice2=1 + (int )(Math.random() * ((6 - 1) + 1));
diceSum=dice1+dice2;
if (diceSum !=7){
theSum=theSum+diceSum;
if (theSum>finalSum){
finalSum=theSum;
}
if (theSum<lowest){
lowest=theSum;
}


}

}
}
System.out.println("After "+args[0]+" simulations: ");
System.out.println("Biggest sum: "+finalSum);
System.out.println("Smallest sum: "+lowest);
}
}

我修好了

public class diceGame {
public static void main(String[] args) {
int dice1;
int dice2;
int count = 0;
int theSum = 0;
int lowest = Integer.MAX_VALUE;
int finalSum = 0;
int diceSum;
int totalSum=0;
while (count < Integer.parseInt(args[0])) {
count = count + 1;
diceSum=0;
theSum=0;
while (diceSum!=7) {
diceSum = 0;
dice1 = 1 + (int) ((Math.random() * (6 - 1)) + 1);
dice2 = 1 + (int) ((Math.random() * (6 - 1)) + 1);
diceSum = dice1 + dice2;
if (diceSum != 7) {
theSum = theSum + diceSum;
}
//System.out.println("the sum is "+theSum);
}
if (theSum > finalSum) {
finalSum = theSum;
}
if (theSum < lowest) {
lowest = theSum;
}
totalSum=totalSum+theSum;
}
double average=(double)totalSum/(Double.parseDouble(args[0]));
System.out.println("After " + args[0] + " simulations: ");
System.out.println("Biggest sum: " + finalSum);
System.out.println("Smallest sum: " + lowest);
System.out.println("The average is: "+average);

}
}

最佳答案

这是因为 2 个骰子相加时的最低值是 2,而不是 0。如果你在第一次掷骰子时掷出 7,那么你将不会更新你的最大和最低值。您需要将这些检查移到循环之外。

        while(diceSum!=7){
diceSum=0;
dice1=1 + (int)(Math.random() * ((6 - 1) + 1));
dice2=1 + (int )(Math.random() * ((6 - 1) + 1));
diceSum=dice1+dice2;
if (diceSum !=7) {
theSum=theSum+diceSum;
}
}
if (theSum>finalSum){
finalSum=theSum;
}
if (theSum<lowest){
lowest=theSum;
}

关于Java掷骰子游戏While循环随机数生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21559777/

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