Math.random() explanation

后端 未结 5 1591
一个人的身影
一个人的身影 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:29

    Here's a method which receives boundaries and returns a random integer. It is slightly more advanced (completely universal): boundaries can be both positive and negative, and minimum/maximum boundaries can come in any order.

    int myRand(int i_from, int i_to) {
      return (int)(Math.random() * (Math.abs(i_from - i_to) + 1)) + Math.min(i_from, i_to);
    }
    

    In general, it finds the absolute distance between the borders, gets relevant random value, and then shifts the answer based on the bottom border.

提交回复
热议问题