Math.random() explanation

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

    If you want to generate a number from 0 to 100, then your code would look like this:

    (int)(Math.random() * 101);
    

    To generate a number from 10 to 20 :

    (int)(Math.random() * 11 + 10);
    

    In the general case:

    (int)(Math.random() * ((upperbound - lowerbound) + 1) + lowerbound);
    

    (where lowerbound is inclusive and upperbound exclusive).

    The inclusion or exclusion of upperbound depends on your choice. Let's say range = (upperbound - lowerbound) + 1 then upperbound is inclusive, but if range = (upperbound - lowerbound) then upperbound is exclusive.

    Example: If I want an integer between 3-5, then if range is (5-3)+1 then 5 is inclusive, but if range is just (5-3) then 5 is exclusive.

提交回复
热议问题