如何在Ruby中获取随机数(How to get a random number in Ruby)

编程入门 行业动态 更新时间:2024-10-26 06:39:46
如何在Ruby中获取随机数(How to get a random number in Ruby)

如何在0和n之间生成随机数?

How do I generate a random number between 0 and n?

最满意答案

rand(range)什么问题?

从Ruby随机数 :

如果您需要一个随机整数来模拟一面六面的模具,您可以使用: 1 + rand(6) 。 可以用2 + rand(6) + rand(6)模拟掷骰子。

最后,如果你只需要一个随机的浮点数,只需调用rand没有参数。


正如Marc-AndréLafortune在下面的回答中所提到的那样, Ruby 1.9.2具有自己的Random类 (Marc-André自己帮助调试 ,因此该功能的1.9.2目标 )。

例如,在你需要猜测10个数字的游戏中 ,您可以使用以下方式初始化它们:

10.times.map{ 20 + Random.rand(11) } #=> [26, 26, 22, 20, 30, 26, 23, 23, 25, 22]

注意:

马克 - 安德烈·拉福顿 ( Marc-AndréLafortune )再次详细解释(使用Random.new )通常使用Random.new.rand(20..30) (使用Random.new )并不是个好主意。

但是如果不使用Random.new ,那么类方法rand只会在注释中指出一个max ,而不是一个Range ,而不是一个Range 。 只有实例方法可以采用Range ,如通过生成一个7位数的随机数来说明的。

这就是为什么Random.new.rand(20..30)的等价物将是20 + Random.rand(11) ,因为Random.rand(int)返回“大于或等于零并小于参数 “ 20..30包括30,我需要提出一个0到11之间的随机数,不包括11。

Use rand(range)

From 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 with 2 + rand(6) + rand(6).

Finally, if you just need a random float, just call rand with no arguments.


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).

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]

Note:

Using Random.new.rand(20..30) (using Random.new) generally would not be a good idea, as explained in detail (again) by Marc-André Lafortune, in his answer (again).

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.

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.

更多推荐

本文发布于:2023-08-03 21:56:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1401112.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:随机数   如何在   number   Ruby   random

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!