如何使变量有 50% 的机会成为一个值,50% 的机会成为另一个值

How do you make a variable have a 50 percent chance of being one value and 50 percent chance of being another?

本文关键字:机会 一个 何使 另一个 变量      更新时间:2023-09-26
 a = document.getElementById("find").value
    if (a == 'Spark' || a == 'Fire') {
        var monster = x
        var player = y
        var damage = Math.floor(Math.random() * 25)
        var damageplayer = Math.floor(Math.random() * 30)
        alert('Your squad succeeded the enemy has ' + (x = x - damage) + ' original territories!');
    alert ('You have' + (y = y - damageplayer) + 'original territories!'); }

这是我上面的代码,我正在尝试使损坏是否= Math.Floor(math.random (( *25( 或 = 0 的几率为 50/50。我尝试将数学 .random 乘以 1,然后将数学乘以 25,但没有奏效。你如何让它在 50% 的时间内等于 0,另外 50% 的时间等于 math.random * 25?

这里有一种方法:

var coin = function() {
    return (Math.random() < 0.5 ? 0 : 1);
}
var damage = 25*coin();

有时我想知道 Math.random 到底有多随机......

另一种选择:

return (new Date((.getMilliseconds(( % 2(;

不要使用 floor(),因为它总是向下舍入。使用round()

var zeroOrOne = Math.round(Math.random());
var damage = zeroOrOne * Math.floor(Math.random() * 25);

或者,如果您是"将尽可能多的代码塞进一行"的人之一:

var damage = Math.round(Math.random()) * Math.floor(Math.random() * 25);
damage = (Math.random() < 0.5) ? 0 : (Math.random() * 25);

尝试使用

var aux = Math.random()
if (aux < 0,5){
    aux = 0
}else{
   aux = damage
}

然后,您可以将 var aux 用于您的 porpose 而不是损坏

我找到了一种方法:

Math.random();
if(Math.random() >= 0.5){ ''set variable to value A }
else { ''set variable to value B }

由于Math.random会随机选择一个数字0 1所以我将检查设置为中途,即0.5