所以,我想知道我到底做错了什么?它给出了类似于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...?
}发布于 2016-11-07 04:03:16
Math.random返回0(包含)到1 (exclusive)之间的随机值。要获得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
发布于 2016-11-07 04:30:33
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;
}好的回复可以在@ Generate random number between two numbers in JavaScript上找到
https://stackoverflow.com/questions/40453801
复制相似问题