今天想搞个随机数
自己想用获得1或0就直接用
Math.floor(Math.random() * 10%2 )*100) ;//获得1或0
接着我想把数值放大 。想获得0-199,利用上一条0或1代替百位数,然后十位个位继续用随机数,最开始我是
const i = parseInt(Math.random() * 10)+ Math.random() * 100+ Math.floor(Math.random() * 10 % 2) * 100);//199内尝试
但发现不对,这样的话个位和十位的数可能出现小数点后的数,加起来可能导致变化,最坏情况就是个位十位都出现了9.99,加起来就有9.99+99.9=109.89,当后面是1的时候这个数值范围变成0-209了与我初衷不符,因此加上Math.floor()提前限制掉,直接将9.99截成9最大就变成199了
const i = parseInt(Math.floor(Math.random() * 10) + Math.floor(Math.random() * 100)+ Math.floor(Math.random() * 10 % 2) * 100);//199
我想范围更大些,这样算也总限制死自己。百度后发现https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Math/random
这老哥这个似乎看起来比我科学多了,记录下来以备后用
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
console.log(getRandomInt(326));//326之间伪随机
//得到小于等于某数的随机整数
getRandomInt: function(max) {
return Math.floor(Math.random() * Math.floor(max));
},
//得到一个两数之间的随机整数
getRandomInt2: function(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //不含最大值,含最小值
},
//得到一个两数之间的随机整数,包括两个数在内
getRandomIntInclusive: function(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值
},
//得到一个两数之间的随机数
getRandomArbitrary: function(min, max) {
return Math.random() * (max - min) + min;
},
//1或0随机数生成
getRandomoz: function() {
return Math.floor(Math.random() * 10 % 2)
}