Lua 整数不会累加。

我有一个简单的 Lua 函数旨在解决连续质数之和的问题。质数41可表示为六个连续质数之和:

41 = 2 + 3 + 5 + 7 + 11 + 13

这是最长的连续质数和,其和小于一百。这是我的函数:

function numOfConsecPrimes(limit)

    a = allPrimes(limit/2)
    length = table.getn(a)
    sumSoFar = 0    innerSum = 0    finalSum = 0
    pos = 1
    items = 0       innerItems = 0  finalItems = 0
    resetpos = pos

    while resetpos < length do
    pos = resetpos
    resetpos = resetpos + 1
    items = 0
    sumSoFar = 0
        while sumSoFar < limit and pos < length do
            if isPrime(sumSoFar) == true then innerSum = sumSoFar innerItems = items end
            print(sumSoFar)
            sumSofar = sumSoFar + a[pos]
            print(a[pos] .."->"..sumSoFar)
            pos = pos + 1
            items = items + 1
        end
    if innerItems > finalItems then finalItems = innerItems finalSum = innerSum  end
    end
end

但是由于某种原因,sumSoFar 永远不会改变。我在 a[pos] 加法之前和之后都打印它,它总是保持为零。正如你看到的,我正在打印 a[pos],值是正确的。所以发生了什么?

点赞
用户240313
用户240313

如果这就是你的代码,那么你只是打错了字。

sumSofar = sumSoFar + a[pos]

将第一个sumSofarf大写,这样它就可以和所有其他的一样了。

2013-08-19 16:59:13