所以,我想知道我在这里做错了什么?它给了我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...?
}
答案 0 :(得分:0)
Math.random返回0(包括)和1(独占)之间的随机值。要获得从7到10的数字,您需要指定最大值,减去min 然后将最小值添加到结果:
此调整后的代码会返回您所在范围内的随机损失。 请记住:如果您确实想要获得最多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()
答案 1 :(得分:0)
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;
}
找到好的回复