有没有办法用JavaScript生成指定范围内的随机数?

例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。


当前回答

我在搜索用TypeScript编写的随机数生成器,在阅读了所有答案后,我写了这个,希望它对TypeScript程序员有用。

    Rand(min: number, max: number): number {
        return (Math.random() * (max - min + 1) | 0) + min;
    }   

其他回答

重要的

The following code works only if the minimum value is `1`. It does not work for minimum values other than `1`.

如果你想得到一个介于1(且只有1)和6之间的随机整数,你可以计算:

const rndInt=数学地板(Math.random()*6)+1控制台日志(rndInt)

哪里:

1是起始编号6是可能结果的数量(1+start(6)-end(1))

根据@Francisc的答案中的int版本添加具有固定精度版本的float:

function randomFloatFromInterval (min, max, fractionDigits) {
  const fractionMultiplier = Math.pow(10, fractionDigits)
  return Math.round(
    (Math.random() * (max - min) + min) * fractionMultiplier,
  ) / fractionMultiplier
}

so:

randomFloatFromInterval(1,3,4) // => 2.2679, 1.509, 1.8863, 2.9741, ...

对于int答案

randomFloatFromInterval(1,3,0) // => 1, 2, 3

如果您想覆盖负数和正数,并确保其安全,请使用以下方法:

JS解决方案:

function generateRangom(low, up) {
  const u = Math.max(low, up);
  const l = Math.min(low, up);
  const diff = u - l;
  const r = Math.floor(Math.random() * (diff + 1)); //'+1' because Math.random() returns 0..0.99, it does not include 'diff' value, so we do +1, so 'diff + 1' won't be included, but just 'diff' value will be.
  
  return l + r; //add the random number that was selected within distance between low and up to the lower limit.  
}

Java解决方案:

public static int generateRandom(int low, int up) {
        int l = Math.min(low, up);
        int u = Math.max(low, up);
        int diff = u - l;

        int r = (int) Math.floor(Math.random() * (diff + 1)); // '+1' because Math.random() returns 0..0.99, it does not include 'diff' value, so we do +1, so 'diff + 1' won't be included, but just 'diff' value will be.
  
        return l + r;//add the random number that was selected within distance between low and up to the lower limit.      
}

这对我来说很有用,并生成类似Python的random.randit标准库函数的值:


function randint(min, max) {
   return Math.round((Math.random() * Math.abs(max - min)) + min);
}

console.log("Random integer: " + randint(-5, 5));

使用可重用的随机函数。

function randomNum(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
randomNum(1, 6);