Math.random没有返回正确的值

时间:2016-11-06 19:51:23

标签: javascript random

所以,我想知道我在这里做错了什么?它给了我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...?
}

2 个答案:

答案 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()

的详细信息,请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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;

}

可以在Generate random number between two numbers in JavaScript

找到好的回复