生成随机数%10 == 0

时间:2018-03-15 18:47:29

标签: javascript

我正在编写一个简单的游戏,但我遇到了生成值的问题。我需要生成一个介于1和500之间的数字,但只能以10,20,30,40,50等形式生成。我已经编写了这样的功能,但数字调整一次,平均为100页的茶点。我怎么能这样做?



console.log(generatePosition());

function generatePosition() {
    var x = Math.floor(Math.random() * 500) + 1;
    var y = Math.floor(Math.random() * 500) + 1;
			
    if (x % 10 == 0 && x % 10 == 0) {
        var cords = [x, y];
    }
			
    return cords;
}




2 个答案:

答案 0 :(得分:2)

最简单的解决方案可能是生成1到50之间的随机数,然后将其乘以10.因此,您将只获得10到500之间的随机数,正如您所希望的那样: - )

所以,基本上就是这样:

const randomInt = function (min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
};

const randomNumberDivisibleBy10 = randomInt(1, 50) * 10;

console.log(randomNumberDivisibleBy10);
// => Something such as 10, 20, 30, …, 500

所以,你的功能看起来像这样:

const generatePosition = function () {
  const x = randomInt(1, 50) * 10,
        y = randomInt(1, 50) * 10;

  const coordinates = [ x, y ];

  return coordinates;
};

Etvoilà: - )

答案 1 :(得分:-1)

function generatePosition() {

    var x = Math.floor(Math.random() * 500) + 1;
    var y = Math.floor(Math.random() * 500) + 1;
    var x = x - (x % 10);
    var y = y - (y % 10);
    var cords = [x, y];

    return cords;

}

您可以使用:)

相关问题