随机数产生最大值或最小值的方法,用Math.random(),Math.floor来实现

版权声明:所有原创文章未经本人同意不得随意转载,谢谢 https://blog.csdn.net/tangcc110/article/details/84588350

1.问题:总是看见有些同学写的随机数没有最大值或最小值,如:

var result = Math.floor(Math.random()*100) + 1 ;// 说好的0-100,结果0是万年出不来

2.解决办法:

function generationRangerandom(minNumber,maxNumber){// 避免没有最小值或最大值
    var randomResult = 0;
    var firstRandom = Math.random();
    var secondRandom = Math.random();
    randomResult = minNumber + Math.floor(firstRandom * (maxNumber - minNumber)) + ((firstRandom + secondRandom) >= 1 ? 1 : 0);
    return randomResult;
}

Brief summary :

关键代码:(firstRandom + secondRandom) >= 1 ? 1 : 0;

猜你喜欢

转载自blog.csdn.net/tangcc110/article/details/84588350
今日推荐