【问题标题】:Generate random number between range including negative in javascript在javascript中生成范围之间的随机数,包括负数
【发布时间】:2016-10-14 12:54:23
【问题描述】:

我正在尝试设置一个在范围之间创建随机数的函数

我需要让它使用负值,这样我才能做到

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

我怎样才能让它工作?

【问题讨论】:

标签: javascript random range negative-number


【解决方案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
	* 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);

【讨论】:

    【解决方案2】:

    您已经在开头声明了变量“pos”。那你为什么在'else'部分声明它? (var pos = b;)

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

    'pos' 没有任何值。

    【讨论】:

      【解决方案3】:
      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,但是有两种可能的数字return) 并从结果中减去另一个 1,因为您使用的是Math.ceil

      你的 else 子句也重新声明了var pos

      【讨论】:

      • 如果不清楚,这可以通过假设可以生成的最小数字为 0,最高为 pos+neg 来实现。然后我们从结果中取出 neg 并且 0 / 较低的基数现在是 neg 并且最高的 (pos+neg) 变成了 neg。我可能只是让它变得不那么容易理解了。
      • -1:您需要使用Math.floor 进行正确分发,而不是Math.ceil
      【解决方案4】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-27
        • 2017-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-31
        • 1970-01-01
        相关资源
        最近更新 更多