2015-11-03 88 views
0

有沒有一種可能性,即:麻煩的Math.random()

Math.floor(Math.random()*6+1); 

能出來爲7?更具體地說,可以:

Math.random() 

作爲1出來?

+0

.......沒有...... – j08691

+0

該文檔說不。 「...返回範圍[0,1]中的浮點僞隨機數,即從0(包含)到1(不包括)」(不包括)「https://developer.mozilla.org/ EN-US /文檔/網絡/的JavaScript /參考/ Global_Objects /數學/隨機的。 – Marc

+1

由於浮點值的精度有限,存在邊緣情況。如果'Math.random()'返回0.9999999999999999',那麼'0.9999999999999999 * 8 + 1'給出'9'(但是'0.9999999999999999 * 6 + 1'仍然給出'6.999999999999999')。在您的控制檯中試用它。不過,我必須說,我曾經見過這種事情發生在「野外」。 –

回答

2

的Math.random()返回之間的隨機數0(含)和1(獨家)

所以,不,它不能返回1

使用這些公式之一得到你想要的東西:

// Returns a random integer between min (included) and max (excluded) 
Math.floor(Math.random() * (max - min)) + min; 
//Example: get a random number >= 1 and < 7 
Math.floor(Math.random() * (7 - 1)) + 1; //Which is your example 

// Returns a random integer between min (included) and max (included) 
Math.floor(Math.random() * (max - min + 1)) + min; 
//Example: get a random number >= 1 and <= 7 
Math.floor(Math.random() * (7 - 1 + 1)) + 1; 
4

否,根據mozilla.org

// Returns a random number between 0 (inclusive) and 1 (exclusive) 
function getRandom() { 
    return Math.random(); 
} 

或右出標準ECMA-262的:

15.8.2.14隨機()

返回Number有正號的值,大於或者等於0但小於1,使用依賴於實現的算法或策略,在該範圍內隨機地或僞隨機地選擇且近似均勻分佈地選擇。這個函數沒有參數。