【发布时间】:2013-04-29 23:44:37
【问题描述】:
我正试图向一位朋友解释 Java 中的随机数生成器,但他每次运行程序时都得到相同的数字。我创建了自己的更简单版本的同一件事,我也得到了他每次运行程序时得到的完全相同的数字。
我做错了什么?
import java.util.*;
public class TestCode{
public static void main(String[] args){
int sum = 0;
Random rand = new Random(100);
for(int x = 0; x < 100; x++){
int num = (rand.nextInt(100)) + 1;
sum += num;
System.out.println("Random number:" + num);
}
//value never changes with repeated program executions.
System.out.println("Sum: " + sum);
}
}
100 个数字中的最后五个数字是:
40
60
27
56
53
【问题讨论】:
-
我认为使用 Math.random() 更好。
-
您在创建 Random 实例时使用了常量种子。所以当然你会得到相同的数字。
-
@Gere:
Math.random()有什么神奇之处,为什么它比使用 Random 实例更好? -
在这种情况下使用 int num = (int) (Math.random()* 100);似乎更好。就是这样。
-
“任何考虑产生随机数字的算术方法的人当然都处于一种罪恶状态”——约翰·冯·诺依曼