Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Lua:随机:百分比_Lua - Fatal编程技术网

Lua:随机:百分比

Lua:随机:百分比,lua,Lua,我正在创建一个游戏,目前必须处理一些math.randomness 因为我在Lua没那么强,你觉得呢 你能做一个使用给定百分比的math.random的算法吗 我指的是这样的函数: function randomChance( chance ) -- Magic happens here -- Return either 0 or 1 based on the results of math.random end randomChance( 50 ) --

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

因为我在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]的数字

因此,只需将您的“机会”转换为介于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
另一种选择是将上限和下限传递给
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
>函数可能(x)如果math.random(0100)可能(0)
0
>也许(100)
1.

我不会在这里乱搞浮点数;我会使用带有整数参数和整数结果的
math.random
。如果您选择1到100之间的100个数字,您应该得到您想要的百分比:

function randomChange (percent) -- returns true a given percentage of calls
  assert(percent >= 0 and percent <= 100) -- sanity check
  return percent >= math.random(1, 100)   -- 1 succeeds 1%, 50 succeeds 50%,
                                          -- 100 always succeeds, 0 always fails
end
function randomChange(percent)--返回给定调用百分比的true
断言(百分比>=0,百分比=math.random(1100)——1成功1%,50成功50%,
--100总是成功,0总是失败
结束

请记住,
math.random(0100)
将返回一个介于0到100之间的数字,因此101个可能的数字中有1个,因此maybe函数中的x不再是百分比,而是101次机会中的1。
> function maybe(x) if math.random(0,100) < x then print(1) else print(0) end end
> maybe(0)
0
> maybe(100)
1
function randomChange (percent) -- returns true a given percentage of calls
  assert(percent >= 0 and percent <= 100) -- sanity check
  return percent >= math.random(1, 100)   -- 1 succeeds 1%, 50 succeeds 50%,
                                          -- 100 always succeeds, 0 always fails
end