如何生成一个范围内的安全统一随机数?范围可以在 0 到 100 之间。(上限不是 2 的幂)。
java.security.SecureRandom
似乎提供范围 0..2^n
。
最佳答案
你可以做到
Random rand = new SecureRandom()
// 0 to 100 inclusive.
int number = rand.nextInt(101);
或
// 0 inclusive to 100 exclusive.
int number = rand.nextInt(100);
注意:这比说 (int) (rand.nexDouble() * 100)
更有效,因为 nextDouble() 需要创建至少 53 位的随机性,而 nextInt(100) 创建少于 7 位。
关于java - 在 Java 中均匀地生成一个范围内的安全随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28742702/