如何在条件中更改表达式的求值以在Javascript中检查布尔值?

问题描述 投票:0回答:2

我正在创建一个硬币翻转游戏,最后一步是使用数学方法在硬币翻转上获得一个实数。然后更改条件中表达式的求值,以便检查布尔值。有什么办法可以实现这个目标?我究竟做错了什么?

var coinFlip = Math.random();
var choice = window.prompt("Select heads or tails");
if (coinFlip < 0.5) {
    choice === window.console.log("heads");
} else {
    choice === window.console.log("tails");
} if (choice === "heads" && coinFlip < 0.5) {
    window.alert("The flip was heads and you chose heads..you win!");
} else if (choice !== "heads" && coinFlip < 0.5) {
    window.alert(" The flip was heads and you chose tails...you lose!");
} else if (choice !== "tails" && coinFlip > 0.5) {
    window.alert("The flip was tails but you choose heads...you lose!");
} else if (choice === "tails" && coinFlip > 0.5) {
    window.alert("The flip was tails and you chose tails...you win!");  
}
coinFlip = Math.Round(Math.Random);
coinFlip = Boolean(choice);

强文

javascript if-statement conditional coercion
2个回答
0
投票

您可以使用Math.round对随机值进行舍入。

Math.round(coinFlip);

var coinFlip = Math.random();

console.log(Math.round(coinFlip));

var choice = window.prompt("Select heads or tails");
if (coinFlip < 0.5) {
    console.log("heads");
} else {
    console.log("tails");
}

if (choice === "heads" && coinFlip < 0.5) {
    window.alert("The flip was heads and you chose heads..you win!");
} else if (choice !== "heads" && coinFlip < 0.5) {
    window.alert(" The flip was heads and you chose tails...you lose!");
} else if (choice !== "tails" && coinFlip > 0.5) {
    window.alert("The flip was tails but you choose heads...you lose!");
} else if (choice === "tails" && coinFlip > 0.5) {
    window.alert("The flip was tails and you chose tails...you win!");  
}

0
投票

如何完全取消这些数字?你不需要“实心整数”,你需要正面或反面。

Math.random()返回0到1之间的实数 - 如果你Math.round()那么,你将得到01。下面,当舍入数用作数组的索引时,零等于头,一等于尾。

const sides = [ "heads", "tails" ];

function play() {
    var choice = window.prompt("Select heads or tails");
    var flip = sides[ Math.round(Math.random()) ];
    console.log("flip was " + flip);
    if (choice === flip) {
        window.alert("You won with " + choice);
    }
    else {
        window.alert("You lost - your choice was " + choice +
                    " but the flip came up " + flip);
    }
}

play();
© www.soinside.com 2019 - 2024. All rights reserved.