我在 lua 中有這個代碼(對不起,如果它不好)。
function splitIntoTable(inputstr,sep)
local t = {}
for str in string.gmatch(inputstr,"([^" .. sep .. "] )") do
table.insert(t,str)
end
return t
end
function displayList(table)
for k, v in ipairs(table) do
print(table[k])
end
end
local tocalc = "57 38"
print("Inputted: " .. tocalc)
tocalc = "0 " .. tocalc
local workwith = splitIntoTable(tocalc," ")
local did = 0
local doing = 1
local lenOfWorkwith = 0
for k in pairs(workwith) do
lenOfWorkwith = lenOfWorkwith 1
end
repeat
if workwith[doing] == " " then
did = did workwith[doing - 1] workwith[doing 1]
end
doing = doing 1
until doing > lenOfWorkwith
did = math.floor(did 0.5)
print("Result: " .. did)
我知道這有點低效,但我現在只需要它可用。基本上,它應該做的只是加上數字。例如,我輸入57 38,它可以正常作業并給我正確的計算,但是一旦我輸入 3 個數字(例如,57 38 40),它就會崩潰并且沒有給出正確的答案。
uj5u.com熱心網友回復:
load您可以通過使用或loadstring根據您的 Lua 版本顯著簡化此操作。
local tocalc = "57 38 40"
print("Result: " .. load("return " .. tocalc)())
您的演算法正在再次添加中間項。
if workwith[doing] == " " then
did = did workwith[doing - 1] workwith[doing 1]
end
在第一個“ ”上,您將did 57 38是 95。在下一個“ ”上,您將得到did 38 40,導致 38 被添加到最終值兩次。要解決此問題,您應該簡單地查看數字并將它們單獨添加,而不是成對添加。
repeat
if workwith[doing] ~= " " then
did = did workwith[doing]
end
doing = doing 1
until doing > lenOfWorkwith
該演算法還有其他問題,我強烈建議使用上述使用負載的解決方案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/443730.html
下一篇:python中的曲線擬合反函式
