【发布时间】:2020-03-01 07:17:41
【问题描述】:
我很好奇为什么当我生成随机词并签入console.log 时,math.floor 的结果比math.ceil 好。
为什么math.ceil 不能完美运行? math.ceil 与 math.random 不兼容,还是我如何分配字符串元素的数组编号(项)?
【问题讨论】:
标签: javascript math
我很好奇为什么当我生成随机词并签入console.log 时,math.floor 的结果比math.ceil 好。
为什么math.ceil 不能完美运行? math.ceil 与 math.random 不兼容,还是我如何分配字符串元素的数组编号(项)?
【问题讨论】:
标签: javascript math
Math.random() 返回一个小于 1(不包括)但大于 0(包括)的数字
Math.floor(Math.random() * 10); // returns a random integer from 0 to 9
Math.ceil(Math.random() * 10); // returns a random integer from 0 to 10 with a very low chance of 0
如果Math.random 的结果恰好是0,则Math.floor() 和Math.ceil() 都将返回0,但如果Math.random() 的结果是0.00000001,Math.floor() 返回0 和@987654@3返回1。
【讨论】:
Math.ceil(Math.random()*10) 返回 1 到 10
Math.random() 的工作方式,Math.ceil(Math.random()*10) 可以返回 0,但概率极低 (stackoverflow.com/questions/52089553)
如果您使用Math.ceil(Math.random()*10),您将丢失第一个号码,如果您使用Math.floor(Math.random()*10),您将丢失最后一个号码
但是如果你使用Math.round(Math.random()*10)你可以找到0到10个数字
var k=2.1
console.log(Math.ceil(k))
console.log(Math.floor(k))
console.log(Math.round(k))
k=2.6
console.log(Math.ceil(k))
console.log(Math.floor(k))
console.log(Math.round(k))
【讨论】:
Math.round() 的问题是它的最后数字的概率不平衡:0-0.49 => 0(概率:1/6)0.5-1.49 => 1(概率:1/3)1.5-2.49 => 2(概率: 1/3) 2.5-3 => 3 (概率: 1/6)