Performance 哪个Lua函数更适合使用?
我用两种方法把数字四舍五入到小数。第一个函数只是对数字进行四舍五入:Performance 哪个Lua函数更适合使用?,performance,math,lua,Performance,Math,Lua,我用两种方法把数字四舍五入到小数。第一个函数只是对数字进行四舍五入: function round(num) local under = math.floor(num) local over = math.floor(num) + 1 local underV = -(under - num) local overV = over - num if overV > underV then return under else
function round(num)
local under = math.floor(num)
local over = math.floor(num) + 1
local underV = -(under - num)
local overV = over - num
if overV > underV then
return under
else
return over
end
end
接下来的两个函数使用此函数将数字四舍五入为小数:
function roundf(num, dec)
return round(num * (1 * dec)) / (1 * dec)
end
function roundf_alt(num, dec)
local r = math.exp(1 * math.log(dec));
return round(r * num) / r;
end
为什么不简单
function round(num)
return num >= 0 and math.floor(num+0.5) or math.ceil(num-0.5)
end
您只需使用math.ceil(num)
为什么你要用1乘以几次
当舍入数字时,有很多事情要考虑。请研究一下如何处理特殊情况。问题不在于什么函数更简单,而在于使用变量然后在函数中使用它们是否会使代码运行更快?@eadwenyoun这句话没有意义。在代码中有过多的乘法并不一定能让事情变得更快。两次调用math.floor而不是一次调用也不是很有效。乘法通常比函数调用花费更少的时间。我指出了代码中花费时间的一些缺陷。如果您对性能差异感兴趣,请测量时间。。。。