gpt4 book ai didi

java - 掷两个骰子得到 7

转载 作者:行者123 更新时间:2023-12-02 01:17:51 25 4
gpt4 key购买 nike

我正在尝试掷骰子,直到获得 7,然后记录通过试验获得 7 所需的次数。所有试验完成后,我需要对它们进行平均。现在我输入了试验次数,但随后它运行了“for 循环”的第一部分(“试验#1:”),然后不执行任何其他操作。我缺少什么?这是在 dr.Java IDE 中完成的。

***编辑* while 循环后的分号是最初的问题。现在我遇到了另一种情况。该循环产生相同的输出(此处所示)。输入随机数生成器的种子值:

[1]

输入试验次数:

[10]

试验#1:10 次掷出 7。

试验#2:10 次掷出 7。

试验#3:10 次掷出 7。

试验#4:10 次掷出 7。

试验#5:10 次掷出 7。

试验#6:10 次掷出 7。

试验#7:10 次掷出 7。

试验#8:10 次掷出 7。

试验#9:10 次掷出 7。

试验#10:10 次掷骰子得到 7。

10 次试验中的 7 次平均掷出 1.0 次。**

import java.util.*;

public class Geometric {
public static void main(String[] args) {
//create the Scanner and the Random number generator using a given seed
Scanner scnr = new Scanner(System.in);
System.out.println("Enter the seed value for the random number generator:");
int seed = scnr.nextInt();
Random r = new Random(seed);

//TODO: complete the program
System.out.println("Enter the number of trials:");
int trials = scnr.nextInt();

int sum = 0;
int count = 0;
int diceAdded = 0;
for (int i=1;i<=trials;i++) {
System.out.print("Trial #" + i + ": ");

while (diceAdded != 7) {
int dice = r.nextInt(6)+1;
int dice2 = r.nextInt(6)+1;
diceAdded = dice + dice2;
count++;
}
System.out.println(count + " rolls to roll a 7.");
sum = count;
}
double average = (sum/trials);
System.out.println("Average " + average + " rolls to roll a 7 over " + trials + " trials.");
}
}

最佳答案

除了已经指出的分号拼写错误之外,您没有在 for 中重置变量。循环,因此每次迭代都会在相同的值上执行。

通过移动您的 count 来解决此问题和diceAdded变量进入 for循环:

System.out.println("Enter the number of trials:");
int trials = scnr.nextInt();

int sum = 0;

for (int i=1;i<=trials;i++) {
System.out.print("Trial #" + i + ": ");
int count = 0;
int diceAdded = 0;
while (diceAdded != 7) {
int dice = r.nextInt(6)+1;
int dice2 = r.nextInt(6)+1;
diceAdded = dice + dice2;
count++;
}
System.out.println(count + " rolls to roll a 7.");
sum += count;
}

此外,请注意我更改了 sum = countsum += count ,这会将计数加在一起,而不是将值重置为上一次迭代的值 count .

感谢@jrook 指出你的平均函数正在整数除法上运行。您可以通过将其中一个值强制转换为 double 来解决此问题像这样:double average = ((double) sum / trials); 。所以现在不仅输出整数。

输出:

Enter the seed value for the random number generator:
121
Enter the number of trials:
5
Trial #1: 15 rolls to roll a 7.
Trial #2: 19 rolls to roll a 7.
Trial #3: 9 rolls to roll a 7.
Trial #4: 2 rolls to roll a 7.
Trial #5: 2 rolls to roll a 7.
Average 9.4 rolls to roll a 7 over 5 trials.

关于java - 掷两个骰子得到 7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58240691/

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