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


当前回答

别忘了先用srand()为RNG种子。

其他回答

嗯,我想通了。显然有一个内置(?)函数叫做rand:

rand(n + 1)

如果有人回答了更详细的答案,我会将其标记为正确答案。

这个呢?

n = 3
(0..n).to_a.sample

您可以使用ruby rand方法,如下所示:

rand(n+1)

您需要使用n+1,因为rand方法返回任何大于或等于0但小于传递的参数值的随机数。

可以使用rand方法生成随机数。传递给rand方法的参数应为整数或范围,并返回范围内的相应随机数:

rand(9)       # this generates a number between 0 to 8
rand(0 .. 9)  # this generates a number between 0 to 9
rand(1 .. 50) # this generates a number between 1 to 50
#rand(m .. n) # m is the start of the number range, n is the end of number range

你可以做rand(范围)

x = rand(1..5)