3 回答

TA貢獻1828條經(jīng)驗 獲得超6個贊
摘要:由于與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()示例中所有其他范圍的一半。

TA貢獻1884條經(jīng)驗 獲得超4個贊
Math.floor(Math.random() * (max - min + 1)) + min
會給你一個 [min, max] 范圍內的隨機數(shù),因為 Math.random() 給你 [0, 1)。讓我們用 Math.round 代替 Math.floor,Math.random() 給你 [0, 1),如果你乘以 10,你會得到 [0, 10)。這是一個浮點數(shù),如果你把它四舍五入,你會得到 [0, 10] 作為整數(shù)。但是,如果將其四舍五入,則會得到 [0, 10) 作為整數(shù)。
在大多數(shù)隨機函數(shù)中,規(guī)范是返回 [min, max)。
為了回答你的問題,作者使用了Math.floor,如果使用Math.round,隨機數(shù)將在[min, max]而不是[min, max+1]的范圍內。
來自維基百科
區(qū)間 主條目:區(qū)間(數(shù)學) 括號 ( ) 和方括號 [ ] 也可用于表示區(qū)間。符號 {\displaystyle [a,c)} [a, c) 用于表示從 a 到 c 的區(qū)間,該區(qū)間包含 {\displaystyle a} a 但不包括 {\displaystyle c} c。也就是說, {\displaystyle [5,12)} [5, 12) 將是 5 到 12 之間所有實數(shù)的集合,包括 5 但不包括 12。這些數(shù)字可能盡可能接近 12,包括 11.999等等(任何有限數(shù)量的 9),但不包括 12.0。在一些歐洲國家,符號 {\displaystyle [5,12[} [5,12[] 也用于此目的。

TA貢獻1848條經(jīng)驗 獲得超10個贊
Math.floor(Math.random())
將始終返回0
而Math.round(Math.random())
將返回,0 or 1
因此Math.round()
隨機數(shù)將遵循非均勻分布。這可能無法滿足您的需求。
添加回答
舉報