How to use the rand function to make numbers in a specific range?

前端 未结 4 935
深忆病人
深忆病人 2020-11-30 15:22

I would like to make random numbers in a specific range, like \"pick a random number between 18 and 35\"? How can I do that with the rand() function?

4条回答
  •  一个人的身影
    2020-11-30 15:47

    1. Do you want integers-only?
    2. Do you want a uniform distribution?
    3. Do you want to include both 18 and 35 as possible values?
    4. What language would you prefer to use?

    in general, if rand() returns a float value in [0.0 ... 1.0) (that is, you may get values arbitrarily close to 1.0 but not actually 1) then you will want something like

    hi = 36
    lo = 18
    res = int( (hi-lo)*rand() + lo ) # returns random values in 18..35
    

    Note that this will never actually return the hi value - therefore I have incremented it by 1 (ie, you will get all values from 18 to 35 inclusive, but never 36).

    Hope that helps.

提交回复
热议问题