gpt4 book ai didi

java - java中的骰子模拟

转载 作者:行者123 更新时间:2023-12-01 17:55:31 28 4
gpt4 key购买 nike

我正在尝试模拟掷骰子 100 次,并打印我落地了多少个 1/2/3/4/5/6 的结果。到目前为止,这是我的代码:我正在尝试使用 while 循环进行作业,并且我需要使用 (Math.random( )*6 + 1) 来生成数字。

public class RollingDice {

public static void main(String args[]) {

int count = 0; // number of times die was rolled
int count1s = 0; // number of times 1 was rolled
int count2s = 0; // number of times 2 was rolled
int count3s = 0;
int count4s = 0;
int count5s = 0;
int count6s = 0;

while (count < 100) {
count1s = (int) (Math.random( )*6 + 1);
count2s = (int) (Math.random( )*6 + 1);
count3s = (int) (Math.random( )*6 + 1);
count4s = (int) (Math.random( )*6 + 1);
count5s = (int) (Math.random( )*6 + 1);
count6s = (int) (Math.random( )*6 + 1);

count++;

}
System.out.println("Number of times the die was rolled: "+ count);
System.out.println("Number of times 1 was rolled: " + count1s);
System.out.println("Number of times 2 was rolled: " + count2s);
System.out.println("Number of times 3 was rolled: " + count3s);
System.out.println("Number of times 4 was rolled: " + count4s);
System.out.println("Number of times 5 was rolled: " + count5s);
System.out.println("Number of times 6 was rolled: " + count6s);

}
}

我的代码当前打印:

Number of times the die was rolled: 100
Number of times 1 was rolled: 3
Number of times 2 was rolled: 1
Number of times 3 was rolled: 5
Number of times 4 was rolled: 2
Number of times 5 was rolled: 4
Number of times 6 was rolled: 4

正如你所看到的,它滚动了 100 次,但它只保存了 1 次滚动的结果,而不是 100 次,我该如何解决这个问题?

最佳答案

在 while 循环的每次迭代中,您都会重新分配 count1scount2s 等的值。相反,您应该做的是“掷骰子”,然后查看它的值,并增加适当的变量。

while (count < 100) {
int diceRoll = (int) (Math.random() * 6 + 1);
if (diceRoll == 1)
count1s++;
else if (diceRoll == 2)
count2s++;
// ... you get the idea

count++;
}

作为一个有趣的旁注,使用 Java 8 有一种更简单、更酷的方法来做到这一点。

        Stream.generate(() -> (int) (Math.random() * 6 + 1))
.limit(100L)
.collect(Collectors.groupingBy(num -> num,
Collectors.counting()))
.forEach((num, count) -> System.out.println("number of times " + num + " was rolled: " + count));

关于java - java中的骰子模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45272247/

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