Javascript 屠龙者-Math.floor(Math.random()*2)是什么意思?
因此,我在codecademy上完成了屠龙者互动活动,我对“Math.floor(Math.random()*2);”应该做什么感到困惑 这是我的“杀龙者”互动活动的完整代码Javascript 屠龙者-Math.floor(Math.random()*2)是什么意思?,javascript,Javascript,因此,我在codecademy上完成了屠龙者互动活动,我对“Math.floor(Math.random()*2);”应该做什么感到困惑 这是我的“杀龙者”互动活动的完整代码 var slaying = true; var youHit = Math.floor(Math.random() * 2); var totalDamage = 0; while (slaying) { var damageThisRound = Math.floor(Math.random() * 5 + 1);
var slaying = true;
var youHit = Math.floor(Math.random() * 2);
var totalDamage = 0;
while (slaying) {
var damageThisRound = Math.floor(Math.random() * 5 + 1);
if (youHit) {
console.log(“You hit the dragon!”);
totalDamage += damageThisRound;
if (totalDamage >= 4) {
console.log(“You slew the dragon!”);
slaying = false;
} else {
youHit = Math.floor(Math.random() * 2);
}
} else {
console.log(“The dragon defeated you!”);
slaying = false;
}
}
你能描述Math.floor(Math.random()*2)的作用吗?Math.random()函数返回一个浮点数,伪随机数的范围为[0,1],即从0(包括)到但不包括1(排除),然后可以将其缩放到所需的范围。实现将选择随机数生成算法的初始种子;用户无法选择或重置该种子
函数的作用是:返回小于或等于给定数字的最大整数
Math.floor( 45.95); // 45
Math.floor( 45.05); // 45
Math.floor( 4 ); // 4
Math.floor(-45.05); // -46
Math.floor(-45.95); // -46
Math.random(); // 0.7757860020429985
Math.random() * 2 // number from range 0.x to 1.x
Math.floor(Math.random() * 2); // will give from 0 or 1
它只是随机生成数字
0
或1
。我建议您查看如何Math.random()
有效。请记住,卡梅隆,一个真正的屠龙者正确地编排了他的问题格式,并确保每个人都能轻松地阅读你的问题。继续杀戮!可能是《嘿,伙计》的翻版,非常感谢。我有点不明白为什么会是数学。地板(45.95);给45分,不给45分46@CameronSuMath.floor不会像您在答案中看到的那样对正值进行舍入,因此ues将对数字进行trunc另一种方法是Math.ceil将对Math.ceil(45.95)=>46进行舍入