gpt4 book ai didi

java - 为什么我用 Random Run 得到相同的数字?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:22:17 25 4
gpt4 key购买 nike

我正在关注一本书并在这段代码中:

    Random rand = new Random(47);
int i, j, k;
j = rand.nextInt(100) + 1;
System.out.println("j : " + j);
k = rand.nextInt(100) + 1;
System.out.println("k : " + k);

我在本书的输出中有相同的数字,即:

j : 59
k : 56

如果我用

Random rand = new Random();

没有 47 Random Class 产生随机数,没关系,但为什么如果我把数字 47 加入 j = rand.nextInt(100) + 1; 为什么我得到相同的输出书?谢谢

最佳答案

来自documentation :

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.

您可以在 constructor 中指定种子

Creates a new random number generator using a single long seed.

另见:
Pseudorandom number generator - Wikipedia

关于java - 为什么我用 Random Run 得到相同的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41361063/

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