【发布时间】:2016-12-16 01:37:02
【问题描述】:
我对 Javascript 和一般编程比较陌生。今天在编写一个简单的三重掷骰子模拟器时,我遇到了一个我已经解决但我仍然不明白的问题。这是我的代码...
// ROLLING TRIPLES
var diceSides = 6;
var diceOne = Math.floor(Math.random() * diceSides + 1);
var diceTwo = Math.floor(Math.random() * diceSides + 1);
var diceThree = Math.floor(Math.random() * diceSides + 1);
var rolls = 3;
while ((diceOne !== diceTwo) || (diceTwo !== diceThree)) {
console.log("Dice 1: " + diceOne);
diceOne = Math.floor(Math.random() * diceSides + 1);
console.log("Dice 2: " + diceTwo);
diceTwo = Math.floor(Math.random() * diceSides + 1);
console.log("Dice 3: " + diceThree);
diceThree = Math.floor(Math.random() * diceSides + 1);
console.log("Rolling again");
rolls += 3;
}
console.log("Dice 1: " + diceOne);
console.log("Dice 2: " + diceTwo);
console.log("Dice 3: " + diceThree);
console.log("Rolled a triple!!!");
console.log(rolls);
问题是“while”条件: 而 ((diceOne !== diceTwo) || (diceTwo !== diceThree))
使用“||”运算符,程序按预期运行,并在 diceOne = diceTwo = diceThree 时跳出“while”循环,即您掷出三倍。然而,这对我来说没有意义......使用'||'运算符看起来“while”循环将完成,条件评估为假,只有两个骰子相等......
例如它会返回如下结果:
Dice 1: 4
Dice 2: 4
Dice 3: 6
Rolled a triple!!!
因为在这种情况下,diceOne 确实等于 diceTwo,即使 diceTwo 不等于 diceThree。在这种情况下,使用 '||'运算符,我希望 'while' 循环停止,因为它似乎已经满足条件......但它没有,它会返回:
Dice 1: 4
Dice 2: 4
Dice 3: 6
Rolling again
...我对 '&&: 运算符的期望。除了使用 '&&' 运算符之外,代码返回我对 '||' 的期望运营商:
Dice 1: 4
Dice 2: 4
Dice 3: 6
Rolled a triple!!!
代码完成,即使三元组尚未滚动。这就是在我脑海中使用“&&”运算符时的声音...
“如果 diceOne 和 diceTwo AND diceThree 相等,则您掷出了三倍。”
带有'||'运营商...
“如果 diceOne 和 diceTwo 相等,或者 diceTwo 和 diceThree 相等,则您掷出了三倍。”
你显然没有,因为三个骰子中只有两个是相同的。
我知道我会一直说下去……这对我来说有点难以解释。可能有一个非常简单的解释,但它真的让我很烦!
附带说明:是否有任何快捷方式我可以用来多次生成随机数而无需键入 Math.floor(Math.random..... 我无法将它分配给变量并输入变量,因为它会生成一个随机数并在每次遇到变量时使用该数字。有没有更有效的方法来做到这一点??
干杯
【问题讨论】:
标签: javascript boolean logic operators logical-operators