我正在寻找一种方法来找出表中最接近x的值并将其返回。
让我们假设X是x = 15,我们的表有4个值{12,190,1,18},在这种情况下如何返回第一个键和值呢?
x = 15
table = {190, 1, 12, 18}
function NearestValue(table, number)
local smallestSoFar, smallestIndex
for i, y in ipairs(table) do
if not smallestSoFar or (math.abs(number-y) < smallestSoFar) then
smallestSoFar = math.abs(number-y)
smallestIndex = i
end
end
return smallestIndex, table[smallestIndex]
end
index, value = NearestValue(table,x)
print(index)
print(value)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句