在javascript

时间:2016-10-14 12:54:23

标签: javascript random range negative-number

我正在尝试设置一个在范围

之间创建随机数的函数

我需要让它使用负值,所以我可以做

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;
}

我怎样才能让它发挥作用?

4 个答案:

答案 0 :(得分:1)

ASSUMING 您将始终拥有一点价值,此代码将执行这些操作,请参阅下面的评论,并且不要犹豫!

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

答案 1 :(得分: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

您的其他条款也重新声明var pos

答案 2 :(得分:0)

您已声明变量&#39; pos&#39;在一开始。那你为什么要在“其他”中宣布呢?部分? (var pos = b;)

因此,对于这个陈述,  do result = Math.ceil(Math.random()*(pos + neg)) - neg;

&#39; POS&#39;没有任何价值。

答案 3 :(得分:0)

如果要生成介于-50和50之间的数字 - 获取0到100之间的随机数,然后减去50

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

console.log(randomNumber);

相关问题