为什么Math.floor()比Math.round()更受欢迎?[JavaScript]
我在FreeCodeCamp中发现,要解决在某个范围内获取随机整数的问题,可以使用为什么Math.floor()比Math.round()更受欢迎?[JavaScript],javascript,math,range,rounding,Javascript,Math,Range,Rounding,我在FreeCodeCamp中发现,要解决在某个范围内获取随机整数的问题,可以使用Math.floor。四舍五入不准确。它返回的值等于或小于。这不是我想的 这是给定的公式: Math.floor(Math.random()*(max-min+1))+min 有人知道为什么它更适合四舍五入到最接近的整数吗 提前谢谢 Math.floor(Math.random() * (max - min + 1)) + min 将给你一个[min,max]范围内的随机数,因为Math.random()给你[0
Math.floor
。四舍五入不准确。它返回的值等于或小于。这不是我想的
这是给定的公式:
Math.floor(Math.random()*(max-min+1))+min
有人知道为什么它更适合四舍五入到最接近的整数吗
提前谢谢
Math.floor(Math.random() * (max - min + 1)) + min
将给你一个[min,max]范围内的随机数,因为Math.random()给你[0,1]。让我们使用Math.round而不是Math.floor,Math.random()给你[0,1],如果你将它乘以10,你将得到[0,10]。这是一个浮点,如果你把它四舍五入,你将得到[0,10]但是,如果你把它四舍五入,你会得到[0,10]作为整数
在大多数随机函数中,范数是返回[min,max]
为了回答您的问题,作者使用Math.floor,因此如果使用Math.round,随机数将在[min,max]范围内,而不是[min,max+1]
来自维基百科
间歇
主要文章:区间(数学)
括号()和方括号[]也可以用来表示区间。符号{\displaystyle[a,c)}[a,c)用于表示从a到c的区间,该区间包括{\displaystyle a}a,但不包括{\displaystyle c}c。也就是说,{\displaystyle[5,12)}[5,12)是介于5和12之间的所有实数的集合,包括5,但不是12。这些数字可能尽可能接近12,包括11.999等等(任何9的有限数),但不包括12.0。在一些欧洲国家,符号{\displaystyle[5,12[}[5,12][也用于此。摘要:因为使用
Math.round()
时,min
和max
中的值表示不足
让我们举一个例子,分别比较使用
Math.floor()
和Math.random()
时的结果
为了清楚起见,我添加了我们正在比较的两个公式:
min = 0;
max = 3;
result = Math.round(Math.random() * (max - min)) + min;
result = Math.floor(Math.random() * (max - min + 1)) + min;
| result | Math.round() | Math.floor() |
|:------:|:------------:|:------------:|
| 0 | 0.0 - 0.499 | 0 - 0.999 |
| 1 | 0.5 - 1.499 | 1 - 1.999 |
| 2 | 1.5 - 2.499 | 2 - 2.999 |
| 3 | 2.5 - 2.999 | 3 - 3.999 |
您可以看到,
0
和3
使用Math.random()
生成它们的范围仅为其他所有范围in-out示例的一半。Math.floor(Math.random())
将始终返回0
,而Math.round(Math.random())
将返回0或1
,因此使用Math.round()
随机数将遵循非均匀分布。这可能不符合您的需要。楼层操作总是向下舍入,而不是最接近的整数。此外,如果您的目标是只向下舍入,则楼层不关心小数。除了返回的简单数字比较之外,没有其他计算结果是一个整数。您给定的公式是的一个示例,您只想使用(Math.floor()
)向下取整保持在你的范围内。非常感谢!我只是想知道你在哪里或如何找到这个参考@Thomas@UnorthodoxThing什么参考资料?我从个人经验中知道这个问题,并举例说明。说真的吗?你应该记录它或提交报告!o.oDocument什么?那Math.round()
可能会取整,但Math.floor()
不会?提到的“问题”是,由于我在回答中解释的原因,Math.round()
不适用于此项工作。使用的任何方法本身都没有错。