问题描述
如何生成0
和n
之间的随机数?
How do I generate a random number between 0
and n
?
推荐答案
使用 rand(range)
来自 Ruby随机数 :
最后,如果您只需要一个随机浮点数,只需调用不带任何参数的rand
.
Finally, if you just need a random float, just call rand
with no arguments.
Marc-AndréLafortune 所述/questions/198460/how-to-get-a-random-number-in-ruby/2773866#2773866>他在下面的回答(投票), Ruby 1.9.2拥有自己的Random
类(Marc-André本人有助于调试,因此该功能的目标1.9.2 .
As Marc-André Lafortune mentions in his answer below (go upvote it), Ruby 1.9.2 has its own Random
class (that Marc-André himself helped to debug, hence the 1.9.2 target for that feature).
例如,在此需要进行游戏的游戏中猜10个数字,您可以使用以下命令对其进行初始化:
For instance, in this game where you need to guess 10 numbers, you can initialize them with:
10.times.map{ 20 + Random.rand(11) }
#=> [26, 26, 22, 20, 30, 26, 23, 23, 25, 22]
注意:
-
使用
Random.new.rand(20..30)
(使用Random.new
)通常不是一个好主意,正如,在(再次).
Using
Random.new.rand(20..30)
(usingRandom.new
) generally would not be a good idea, as explained in detail (again) by Marc-André Lafortune, in his answer (again).
但是,如果您不使用Random.new
,则类方法rand
仅采用max
值,而不采用Range
,如 banister (大力地)在注释中指出(并在文档中Random
).只有实例方法可以采用Range
,如生成具有7位数字的随机数所示.
But if you don't use Random.new
, then the class method rand
only takes a max
value, not a Range
, as banister (energetically) points out in the comment (and as documented in the docs for Random
). Only the instance method can take a Range
, as illustrated by generate a random number with 7 digits.
这就是为什么Random.new.rand(20..30)
等于20 + Random.rand(11)
的原因,因为Random.rand(int)
返回一个大于或等于0且小于自变量的随机整数". 20..30
包括30,我需要给出一个0到11之间的随机数,不包括11.
This is why the equivalent of Random.new.rand(20..30)
would be 20 + Random.rand(11)
, since Random.rand(int)
returns "a random integer greater than or equal to zero and less than the argument." 20..30
includes 30, I need to come up with a random number between 0 and 11, excluding 11.
这篇关于如何在Ruby中获得随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!