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
        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
点赞
用户2858170
用户2858170

为什么不直接使用以下代码:

function round(num)
  return num >= 0 and math.floor(num+0.5) or math.ceil(num-0.5)
end

说句题外话,你可以使用 math.ceil(num) 代替 math.floor(num) + 1

还有为什么你要多次使用 1 进行乘法操作?

在取整数时,有很多特殊情况需要考虑。请进行一些研究来处理这些情况。

2019-10-29 10:08:35