00:00/
发布于2017-06-11 / 4327次浏览
脚本之家中找到这么一段代码:
生成n-m,包含n和m的随机数:
第一步算出 m-n的值,假设等于w
第二步Math.random()*w
第三步Math.random()*w+n
第四步Math.round(Math.random()*w+n) 或者 Math.ceil(Math.random()*w+n)
但实际上:Math.round(Math.random()*9+1)
原因分析:Math.random()生成的数是随机的,原因出在Math.round上,Math.round是四舍五入,生成1到10的随机数中,(1,1.5)区间上的数才能得到1,而[1.5,2.5)值为2,
所以一头一尾只有其它数一半的机率,所以得改用Math.ceil或floor。
Math.ceil(Math.random()*9+1)
向上取整所以取不到1
比较准确的做法:
Math.floor(Math.random()*10+1);
Math.floor(Math.random()*数量+最小值);
Math.ceil() 返回大于等于数字参数的最小整数(取整函数),对数字进行上舍入
Math.floor() 返回小于等于数字参数的最大整数,对数字进行下舍入
Math.round() 返回数字最接近的整数,四舍五入
by the way:
不知道为什么wordpress会和代码如诗有牵扯。wordpress的代码排版以及文章编辑一直就是软肋。
估计是写错了,应该是:代码如屎吧~
最后修改于:2017年10月21日 上午1:01
初访 念安