根据第二行条件从下面的代码 - 如果骰子 === 6 代码必须停止!在第 4 行重新分配 dice 变量需要什么? (我是个乞丐)
From the code below as per 2nd line condition - if dice === 6 code must stop ! what's the need of reassigning dice variable at line 4 ? (I'm a begnr)
let dice = Math.trunc(Math.random() * 6) + 1;
while (dice !== 6) {
console.log(`you rolled ${dice}`);
dice = Math.trunc(Math.random() * 6) + 1;
if (dice === 6) {
console.log("Game over at 6");
}
}
在第一行,骰子的值在 1-6 之间,如果不是 6,它会进入循环并告诉您掷的是什么。如果我们不重新分配 dice 变量,它会导致第一行的 dice 值相同,并且代码陷入无限循环,因为骰子不是 6,也永远不会是 6。我们需要重新分配它,以便骰子不在第一行可以变成6,结束游戏。
PS。如果第一行的骰子是 6,它不会打印游戏结束。
在第 1 行,你给骰子一个 1 到 6 之间的随机值。
在第 2 行,您声明虽然值不是 6,但您应该执行 while 循环中的操作。
在第 4 行,你给骰子一个 1 到 6 之间的新随机值。
然后你检查代码是否为 6.
我也希望这段代码写得非常糟糕,对编程的理解很差。不要指望从给你的老师那里学习正确的编码。
这里有一个更好的方法。
while true {
let dice;
dice = Math.trunc(Math.random() * 6) + 1;
console.log(`you rolled ${dice}`);
if (dice === 6) {
console.log("Game over at 6");
break; // this will end the while loop
}
}
let dice = Math.trunc(Math.random() * 6) + 1;
while (dice !== 6) {
console.log(`you rolled ${dice}`);
dice = Math.trunc(Math.random() * 6) + 1;
if (dice === 6) {
console.log("Game over at 6");
}
}
在第一行,骰子的值在 1-6 之间,如果不是 6,它会进入循环并告诉您掷的是什么。如果我们不重新分配 dice 变量,它会导致第一行的 dice 值相同,并且代码陷入无限循环,因为骰子不是 6,也永远不会是 6。我们需要重新分配它,以便骰子不在第一行可以变成6,结束游戏。
PS。如果第一行的骰子是 6,它不会打印游戏结束。
在第 1 行,你给骰子一个 1 到 6 之间的随机值。 在第 2 行,您声明虽然值不是 6,但您应该执行 while 循环中的操作。 在第 4 行,你给骰子一个 1 到 6 之间的新随机值。 然后你检查代码是否为 6.
我也希望这段代码写得非常糟糕,对编程的理解很差。不要指望从给你的老师那里学习正确的编码。
这里有一个更好的方法。
while true {
let dice;
dice = Math.trunc(Math.random() * 6) + 1;
console.log(`you rolled ${dice}`);
if (dice === 6) {
console.log("Game over at 6");
break; // this will end the while loop
}
}