2016-10-14 45 views
1

我想設置一個範圍之間生成範圍之間的隨機數,包括在javascript

我需要使它與負值的工作產生一個隨機數的函數負,所以我可以做

randomBetweenRange(10, 20) 
randomBetweenRange(-10, 10) 
randomBetweenRange(-20, -10) 

這就是我想,這是一個有點混亂,目前randomBetweenRange(-20, -10)不工作..

function randomBetweenRange(a, b){ 
    var neg; 
    var pos; 

    if(a < 0){ 
     neg = Math.abs(a) + 1; 
     pos = (b * 2) - 1; 
    }else{ 
     neg = -Math.abs(a) + 1; 
     var pos = b; 
    } 

    var includeZero = true; 
    var result; 

    do result = Math.ceil(Math.random() * (pos + neg)) - neg; 
    while (includeZero === false && result === 0); 

    return result; 
} 

我怎樣才能使它的工作?

+1

可能重複/ questions/1527803 /生成隨機整數 - 在特定範圍內的javascript –

回答

0
do result = Math.ceil(Math.random() * (pos + neg)) - neg; 

具體來說Math.random() * (pos + neg)返回錯誤的範圍。如果pos = -20neg = -30,pos和neg之間的範圍應該是10,但是您的操作返回-50。你也應該添加一個到範圍,因爲它在技術上的可能性的數量(例如:如果你想生成你的函數返回{0,1},pos和neg之間的範圍是1,但有兩個數字的可能性返回),並從結果中減去另一1,因爲你使用Math.ceil

你的其他條款也redeclares var pos

+1

如果不清楚,這可以通過假設可生成的最低數量爲0,最高爲pos +負。然後,我們將負值從結果中取出,並且0 /下基底現在爲負值,最高值(pos + neg)變爲負值。我可能只是讓它變得不那麼容易理解。 –

+0

-1:您需要使用'Math.floor'來獲得正確的分佈,而不是'Math.ceil' – Bergi

1

基於假設你總是有第一次的小值,該代碼將做技巧,請參見評論如下,不要猶豫,問!

var a=parseInt(prompt("First value")); 
 
var b=parseInt(prompt("Second value")); 
 
var result = 0; 
 

 
// Here, b - a will get the interval for any pos+neg value. 
 
result = Math.floor(Math.random() * (b - a)) + a; 
 
/* First case is we got two neg value 
 
\t * We make the little one pos to get the intervale 
 
\t * Due to this, we use - a to set the start 
 
*/ 
 
if(a < 0) { 
 
\t if(b < 0) { 
 
\t \t a = Math.abs(a); 
 
\t \t result = Math.floor(Math.random() * (a + b)) - a; 
 
\t } 
 
/* Second case is we got two neg value 
 
\t * We make the little one neg to get the intervale 
 
\t * Due to this, we use - a to set the start 
 
*/ 
 
} else { 
 
\t if(b > 0) { 
 
\t \t a = a*-1; 
 
\t \t result = Math.floor(Math.random() * (a + b)) - a; 
 
\t } 
 
} 
 
console.log("A : "+a+" | B : "+b+" | Int : "+(a+b)+"/"+Math.abs((a-b))); 
 
console.log(result);

0

你已經宣佈在一開始本身的變量的POS'。那麼你爲什麼要在「其他」部分聲明呢? (var pos = b;)

因此,對於此語句, do result = Math.ceil(Math.random()*(pos + neg)) - neg;

'pos'將沒有任何價值。

0

如果你想生成-50和50之間的數字 - 獲取然後0和100之間的隨機數減去http://stackoverflow.com 50

var randomNumber = Math.floor(Math.random() * 101) - 50; 
 

 
console.log(randomNumber);

相關問題