ddk*_*ddk 28 floating-point lua
尽管Lua没有区分浮点数和整数,但有些情况下你想要使用整数.如果你不能做一个类似C的演员或没有类似Python的东西,将数字转换为整数的最佳方法是什么int
?
例如,在计算数组的索引时
idx =位置/宽度
你怎么能确保idx
有效的数组索引?我提出了一个使用的解决方案string.find
,但也许有一种使用算法的方法显然会更快.我的解决方案
function toint(n)
local s = tostring(n)
local i, j = s:find('%.')
if i then
return tonumber(s:sub(1, i-1))
else
return n
end
end
Run Code Online (Sandbox Code Playgroud)
小智 6
@Hofstad是正确的,math.floor(Number x)
建议消除小数点右边的位,你可能想要舍入.没有math.round
,但它很简单math.floor(x + 0.5)
.你想要舍入的原因是浮动通常是近似的.例如,1
可能是0.999999996
12.4 + 0.5 = 12.9,地板12
12.5 + 0.5 = 13,地板13
12.6 + 0.5 = 13.1,地板13
local round = function(a, prec)
return math.floor(a + 0.5*prec) -- where prec is 10^n, starting at 0
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
69209 次 |
最近记录: |