performance - 哪个 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
解决方案
为什么不简单
function round(num)
return num >= 0 and math.floor(num+0.5) or math.ceil(num-0.5)
end
而不是math.floor(num) + 1
你可以简单地使用math.ceil(num)
顺便说一句。
为什么要多次乘以 1?
四舍五入时需要考虑很多事情。请研究如何处理特殊情况。
推荐阅读
- docker - GKE 容器占用的内存多于分配给它的内存
- javascript - 从 DOM 元素中删除字符
- oracle11g - 将数据从另一个现有表插入对象类型表..Oracle 11g
- php - 如果上传则更新图像,否则使用先前存储的图像
- javascript - 在使用 drupal 的用户列表中显示所选用户的详细信息
- java - 在android中显示office文档
- printing - 在一个字段中打印反斜杠和 unicode 字符
- javascript - asp.net 客户控制和 javascript
- python - 给定字符串 = 欢迎使用 python。我希望输出为'welcome-to-python',在以下代码中出现错误
- c# - 统一 C#。无法从另一个脚本调用