[英]Math.random not returning the right value
所以,我想知道我在做什么错吗? 它给我的数字是3。(我将变量a传递为“ 7-10”)
function getDmg(a, y) {
var s = Math.floor((Math.random() * (a.split('-')[1])) + (a.split('-')[0]));
if(y == true) {
console.log('You dealt ' + s + ' damage.');
} else {
console.log('You took ' + s + ' damage.');
}
return s; // Giving numbers like 3...?
}
Math.random返回介于0(含)和1( 不含 )之间的随机值。 要获得7到10之间的数字,您需要指定最大值,减去最小值,然后将最小值添加到结果中 :
调整后的代码会返回您范围内的随机损失。 请记住:如果确实希望最大为10,则需要传递11作为Math.random
的上限,因为该上限是独占的 :
function getDmg(a, y) { var min = parseInt(a.split('-')[0],10); var max = parseInt(a.split('-')[1],10); var s = Math.floor(Math.random() * (max - min) + min); if(y == true) { console.log('You dealt ' + s + ' damage.'); } else { console.log('You took ' + s + ' damage.'); } return s; // Giving numbers like 3...? } getDmg("7-11", true); getDmg("7-11", false);
有关Math.random()
更多详细信息,请参见: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
function getDmg(range, dealt) {
var damageRange = range.split("-");
//This will have to be made more "error-proof"
var min = Number(damageRange[0]);
var max = Number(damageRange[1]);
//This formula will take the min and max into account
var calculatedDamage = Math.floor(Math.random() * (max - min + 1)) + min;
console.log((dealt ? "You dealt " : "You took ") + calculatedDamage + " damage.");
return calculatedDamage;
}
可以找到良好的答复@ 在JavaScript中生成两个数字之间的随机数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.