【问题标题】:Lua 5.1.4 math.random not actually randomLua 5.1.4 math.random 实际上不是随机的
【发布时间】:2015-08-18 22:48:54
【问题描述】:

我的问题是当我写 math.random(10) 它实际上并不是随机的,它总是给我输出:

1 6 2 9

如果我用过例如:

local colors = {"ORANG","BLUE","RED","YELLOW","BLACK"}
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
os.execute 'pause'

输出总是:

ORANGE
RED
ORANGE
BLACK
RED
RED
BLUE BLACK

这总是输出,怎么可能是随机的???

【问题讨论】:

标签: function math random lua


【解决方案1】:

我找到了答案,你需要输入:

math.randomseed(os.time())
math.random(); math.random(); math.random()

在使用 math.random() 之前

【讨论】:

  • 但请确保在您的程序中只调用math.randomseed一次,而不是每次调用math.random
【解决方案2】:

你误解了random 的作用:

这是一个伪随机数生成器。这意味着,给定一个特定的seed,它将始终为您提供完全相同的相同数字序列。

通常,您使用来自外部来源的种子,例如使用当前时间作为种子(警告:这在密码学上很危险!)。

请阅读伪随机以及如何使用 Lua 的随机库。

【讨论】:

    猜你喜欢
    • 2015-11-06
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 2014-04-30
    • 2011-01-21
    相关资源
    最近更新 更多