【问题标题】:Random seed Math.random in JavaJava中的随机种子Math.random
【发布时间】:2013-07-03 10:38:24
【问题描述】:

在我的代码中,我在不同的类中使用随机数。如何定义随机种子?我可以为主代码中的所有类定义这个种子吗?

double rnd = Math.random();

【问题讨论】:

    标签: java random random-seed


    【解决方案1】:

    您可能想要使用特殊的 Random 类。它使您可以更好地控制随机数。 为此,您首先需要创建一个新的随机对象。

    Random generator = new Random(seed);
    

    然后通过

    生成一个新号码
    double random = generator.nextDouble();
    

    http://docs.oracle.com/javase/6/docs/api/java/util/Random.html

    【讨论】:

      【解决方案2】:
      public class MathRandomWithSeed {
      
          public static void main (String args[]){
      
              int min = 5;
              int max = 100;
              int seed = 5;
              
              int random = randomNext(min, max, seed);
      
              System.out.println("Random = " + random);
          }
      
          private static int randomNext(int min, int max, int seed){
      
              int count = (max - min) / seed;
      
              int random = ((int)(count * Math.random()) * seed) + min;
      
              return random;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2016-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-09
        • 2014-04-30
        • 1970-01-01
        相关资源
        最近更新 更多