Math.random() explanation

后端 未结 5 1471
一个人的身影
一个人的身影 2020-11-22 07:02

This is a pretty simple Java (though probably applicable to all programming) question:

Math.random() returns a number between zero and on

5条回答
  •  灰色年华
    2020-11-22 07:46

    int randomWithRange(int min, int max)
    {
       int range = (max - min) + 1;     
       return (int)(Math.random() * range) + min;
    }
    

    Output of randomWithRange(2, 5) 10 times:

    5
    2
    3
    3
    2
    4
    4
    4
    5
    4
    

    The bounds are inclusive, ie [2,5], and min must be less than max in the above example.

    EDIT: If someone was going to try and be stupid and reverse min and max, you could change the code to:

    int randomWithRange(int min, int max)
    {
       int range = Math.abs(max - min) + 1;     
       return (int)(Math.random() * range) + (min <= max ? min : max);
    }
    

    EDIT2: For your question about doubles, it's just:

    double randomWithRange(double min, double max)
    {
       double range = (max - min);     
       return (Math.random() * range) + min;
    }
    

    And again if you want to idiot-proof it it's just:

    double randomWithRange(double min, double max)
    {
       double range = Math.abs(max - min);     
       return (Math.random() * range) + (min <= max ? min : max);
    }
    

提交回复
热议问题