在 lua 中 for 循环中有没有一种方法在变量中添加数值?

我编写了这个程序:

a = math.random(0, 9) - 0 -- 在这个阶段,如果结果等于零,那么就是匹配
b = math.random(0, 9) - 1
c = math.random(0, 9) - 2
d = math.random(0, 9) - 3
e = math.random(0, 9) - 4
f = math.random(0, 9) - 5
g = math.random(0, 9) - 6
h = math.random(0, 9) - 7
i = math.random(0, 9) - 8
j = math.random(0, 9) - 9

print("输入您想要模拟的试验次数。") -- 这是我决定要进行多少次试验的地方

var = io.read()

a_ = 0 -- 这是我希望在这里保留"a"匹配次数的地方,"b"匹配次数的数量等等。 频率
b_ = 0
c_ = 0
d_ = 0
e_ = 0
f_ = 0
g_ = 0
h_ = 0
i_ = 0
j_ = 0

for k = 1, var do -- 一个循环是一个试验

    print("Trail #"..k)

    if a == 0 then
        print("a = 匹配")
    elseif a ~= 0 then
        print("a = 不匹配")
    end

    if b == 0 then
        print("b = 匹配")
    elseif b ~= 0 then
        print("b = 不匹配")
    end

    if c == 0 then
        print("c = 匹配")
    elseif c ~= 0 then
        print("c = 不匹配")
    end

    if d == 0 then
        print("d = 匹配")
    elseif d ~= 0 then
        print("d = 不匹配")
    end

    if e == 0 then
        print("e = 匹配")
    elseif e ~= 0 then
        print("e = 不匹配")
    end

    if f == 0 then
        print("f = 匹配")
    elseif f ~= 0 then
        print("f = 不匹配")
    end

    if g == 0 then
        print("g = 匹配")
    elseif g ~= 0 then
        print("g = 不匹配")
    end

    if h == 0 then
        print("h = 匹配")
    elseif h ~= 0 then
        print("h = 不匹配")
    end

    if i == 0 then
        print("i = 匹配")
    elseif i ~= 0 then
        print("i = 不匹配")
    end

    if j == 0 then
        print("j = 匹配")
    elseif j ~= 0 then
        print("j = 不匹配")
    end

end

while true do -- 这只是为了在程序完成后保持窗口打开以便我可以观察数据,您可以忽略此项
end

正如您所看到的,我尝试每当它返回零的结果时,将一加到 a_、b_ 和 c_ 中,但它不起作用,有没有一种方法可以做到这一点? 我之所以想要做这个是因为我正在上一门 AP 统计课,这将使这个问题变得更容易。 我现在只做 a_、b_、c_,一旦解决了这个问题,我会做所有的数据。 谢谢阅读!

点赞
用户88888888
用户88888888

如果您想要模拟运行“ var”次,请尝试以下操作:

math.randomseed(os.time())

local matchStorage = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
local randomNums = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}

local function runSimulation(numTrial)
    print("\n运行试验#: " .. numTrial)

    for index, value in pairs(randomNums) do
        local variable = math.random(0, 9)
        randomNums[index] = variable
    end

    for index, value in pairs(randomNums) do
        if randomNums[index] == 0 then
            matchStorage[index] = matchStorage[index] + 1
            print("索引 " .. index .. " 匹配。")
        else
            print("索引 " .. index .. " 不匹配。")
        end
    end
end

do
    print("输入试验次数")
    numTrials = io.read()

    for index = 1, numTrials do
        runSimulation(index)
    end

    print("\n结果:\n")

    for index, value in pairs(matchStorage) do
        print("索引 " .. index .. " 频率: " .. value)
    end
end

以下'randomNum'值中包含0的次数将存储在其对应的'matchStorage'索引中。

2016-02-21 19:44:57