gpt4 book ai didi

Lua:随机:百分比

转载 作者:行者123 更新时间:2023-12-02 02:35:07 27 4
gpt4 key购买 nike

我正在创建一个游戏,目前必须处理一些math.random问题。

我的Lua能力不是那么强,你觉得怎么样

  • 您能制定一个使用 math.random 和给定百分比的算法吗?

我的意思是这样的函数:

function randomChance( chance )
-- Magic happens here
-- Return either 0 or 1 based on the results of math.random
end
randomChance( 50 ) -- Like a 50-50 chance of "winning", should result in something like math.random( 1, 2 ) == 1 (?)
randomChance(20) -- 20% chance to result in a 1
randomChance(0) -- Result always is 0

但是我不知道如何继续,而且我完全不擅长算法

我希望你能理解我对我想要实现的目标的错误解释

最佳答案

如果没有参数,math.random 函数将返回 [0,1) 范围内的数字。

Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> =math.random()
0.13153778814317
> =math.random()
0.75560532219503

因此,只需将您的“机会”转换为 0 到 1 之间的数字:即

> function maybe(x) if math.random() < x then print("yes") else print("no") end end
> maybe(0.5)
yes
> maybe(0.5)
no

或者将random的结果乘以100,与0-100范围内的int进行比较:

> function maybe(x) if 100 * math.random() < x then print(1) else print(0) end  end                                                                             
> maybe(50)
0
> maybe(10)
0
> maybe(99)
1

另一种选择是将上限和下限传递给 math.random:

> function maybe(x) if math.random(0,100) < x then print(1) else print(0) end end
> maybe(0)
0
> maybe(100)
1

关于Lua:随机:百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2986179/

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