如何在javascript中生成两个随机数,例如第一个数字始终大于第二个数字?

时间:2019-11-30 09:55:12

标签: javascript

如何在javascript中生成两个随机数,例如第一个数字总是大于第二个,并且在另一个代码中,请分享如何生成两个随机数,例如第一个数字总是被第二个整除?

我正在尝试

var x = (Math.floor(Math.random() * 100) + 1);
var y = ((Math.floor(Math.random() * 100) + 1) <= x);

console.log(x, y);

但是我只得到x的值,而不是得到y的值,我得到的是对还是错。

2 个答案:

答案 0 :(得分:1)

您可以先获取一个数字,然后获取其一部分,然后从部分中选择一个值。

function getRandomN(max) {
    return Math.floor(Math.random() * max) + 1;
}

function getRandom(array) {
    return array[Math.floor(Math.random() * array.length)];
}

function getParts(n) {
    var parts = [],
        i;

    for (i = 1; i < Math.floor(n / 2); i++) {
        if (n % i === 0) parts.push(i);
    }
    console.log(...parts);
    return parts;
}

var value1 = getRandomN(100),
    value2 = getRandom(getParts(value1));

console.log(value1, value2);

答案 1 :(得分:0)

我将使用randojs.com来回答这个问题,因此,如果您想使用我的回答,请将其放在HTML文档的head标签中:

<script src="https://randojs.com/1.0.0.js"></script>

获取两个随机数1-100,其中第二个总是更大:

var x = rando(1, 99);
var y = rando(x + 1, 100);

获取两个随机数1-100,其中第二个总是被第一个整除:

var a = 2, b = 3;
while(b / a % 1 > 0){
    a = rando(1, 100);
    b = rando(1, 100);
}

如果您想要的是该部门代码的版本,效率更高一点,但处理起来会更漫长:

var a = rando(1, 100);
var b = rando(1, 100);
while(a * b > 100 && a / b % 1 > 0 && b / a % 1 > 0){
    a = rando(1, 100);
    b = rando(1, 100);
}
if(b / a % 1 > 0){
    if(a / b % 1 == 0){
        var temp = a;
        a = b;
        b = temp
    }
    else{
        b = a * b;
    }
}