- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
如何生成介于 0
和 n
之间的随机数?
最佳答案
来自 Ruby Random Numbers :
If you needed a random integer to simulate a roll of a six-sided die, you'd use:
1 + rand(6)
. A roll in craps could be simulated with2 + rand(6) + rand(6)
.Finally, if you just need a random float, just call
rand
with no arguments.
作为Marc-André Lafortune在 his answer below (go upvote it) 中提到, Ruby 1.9.2 has its own Random
class (即 Marc-André 本人 helped to debug,因此该功能的 1.9.2 target)。
例如,在这个game where you need to guess 10 numbers ,您可以使用以下方法初始化它们:
10.times.map{ 20 + Random.rand(11) }
#=> [26, 26, 22, 20, 30, 26, 23, 23, 25, 22]
注意:
Using Random.new.rand(20..30)
(使用 Random.new
)通常不是一个好主意,如详细说明(再次)Marc-André Lafortune , 在 his answer (再次)。
但是如果你不使用Random.new
,那么class method rand
仅采用 max
值,而不是 Range
,如 banister (积极地)在评论中指出(并在 docs for Random
中记录)。只有 instance method可以采用 Range
,如 generate a random number with 7 digits 所示.
这就是为什么 Random.new.rand(20..30)
的等价物是 20 + Random.rand(11)
,因为 Random .rand(int)
返回“一个大于或等于零且小于参数的随机整数。” 20..30
包括 30,我需要想出一个介于 0 和 11 之间的随机数,不包括 11。
关于ruby-on-rails - 如何在 Ruby 中获取随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/198460/
我是一名优秀的程序员,十分优秀!