gpt4 book ai didi

ruby-on-rails - 如何在 Ruby 中获取随机数

转载 作者:数据小太阳 更新时间:2023-10-29 06:16:04 24 4
gpt4 key购买 nike

如何生成介于 0n 之间的随机数?

最佳答案

使用rand(range)

来自 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.


作为Marc-André Lafortunehis 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]

注意:

这就是为什么 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com