Generate random number between two numbers in Java

2018-12-31 05:16发布

Is there a way to generate a random number in a specified range (e.g. from 1 to 6: 1, 2, 3, 4, 5, or 6) in JavaScript?

18条回答
墨雨无痕
2楼-- · 2018-12-31 05:45

If you wanted to get between 1 and 6, you would calculate:

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

Where:

  • 1 is the start number
  • 6 is the number of possible results (1 + start (6) - end (1))
查看更多
宁负流年不负卿
3楼-- · 2018-12-31 05:45

Math is not my strong point, but I've been working on a project where I needed to generate a lot of random numbers between both positive and negative.

function randomBetween(min, max) {
    if (min < 0) {
        return min + Math.random() * (Math.abs(min)+max);
    }else {
        return min + Math.random() * max;
    }
}

E.g

randomBetween(-10,15)//or..
randomBetween(10,20)//or...
randomBetween(-200,-100)

Of course, you can also add some validation to make sure you don't do this with anything other than numbers. Also make sure that min is always less than or equal to max.

查看更多
闭嘴吧你
4楼-- · 2018-12-31 05:46

I wrote more flexible function which can give you random number but not only integer.

function rand(min,max,interval)
{
    if (typeof(interval)==='undefined') interval = 1;
    var r = Math.floor(Math.random()*(max-min+interval)/interval);
    return r*interval+min;
}

var a = rand(0,10); //can be 0, 1, 2 (...) 9, 10
var b = rand(4,6,0.1); //can be 4.0, 4.1, 4.2 (...) 5.9, 6.0

Fixed version.

查看更多
柔情千种
5楼-- · 2018-12-31 05:49

Example

Return a random number between 1 and 10:

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

The result could be: 3

Try yourself: here

--

or using lodash / undescore:

_.random(min, max)

Docs: - lodash - undescore

查看更多
泪湿衣
6楼-- · 2018-12-31 05:50

I found Francisc's solution above did not include the min or max number in the results, so I altered it like this:

function randomInt(min,max)
{
    return Math.floor(Math.random()*(max-(min+1))+(min+1));
}
查看更多
孤独总比滥情好
7楼-- · 2018-12-31 05:52

jsfiddle: https://jsfiddle.net/cyGwf/477/

Random Integer: to get a random integer between min and max, use the following code

function getRandomInteger(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
}

Random Floating Point Number: to get a random floating point number between min and max, use the following code

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

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

查看更多
登录 后发表回答