math.random(1, 100) 只给我十进制数字

我正在制作一个需要人们猜测随机生成数字的程序。但是,这是不可能的,因为计算机只会生成极长的十进制数字。有没有办法让 math.random(1, 100) 只生成整数?

点赞
用户11193682
用户11193682
函数名:round(num, numDecimalPlaces)

参数:
- num:需要进行四舍五入的数值
- numDecimalPlaces:保留的小数点位数,默认为0

返回值:四舍五入后的结果

实现代码:

function round(num, numDecimalPlaces)
  local mult = 10^(numDecimalPlaces or 0)
  return math.floor(num * mult + 0.5) / mult
end

使用示例:

- round(1023.4345, -2) = 1000
- round(1023.4345, 2) = 1023.43
2019-03-14 01:45:45