嗨,我想在 JavaScript 中生成 -x 和 x 之間的亂數。這就是我所擁有的:
function randomInt(nb){
let absoluteVal = Math.ceil(Math.random()*nb)
let sign = Math.floor(Math.random()*2)
return sign == 1 ? absoluteVal*(-1) : absoluteVal;
}
console.log(randomInt(4))
它有效,但它相當不優雅。我想知道是否有人知道更好的解決方案。提前致謝。
uj5u.com熱心網友回復:
例如n = 4,它會生成以下值:
-4 -3 -2 -1 0 1 2 3 4
在總9元素。通過使用正值,它生成0...8偏移量為-4。
function randomInt(n) {
return Math.floor(Math.random() * (2 * n 1)) - n;
}
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
.as-console-wrapper { max-height: 100% !important; top: 0; }
uj5u.com熱心網友回復:
Using Math.random()(returns an random number between 0 and 1) 允許您這樣做( usingMath.ceil()用于將數字四舍五入到下一個最大整數)
function randomInt(nb){
return Math.ceil(Math.random() * nb) * (Math.round(Math.random()) ? 1 : -1)
}
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
更多關于Math.ceil()- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil
更多關于Math.random()- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/343358.html
標籤:javascript 数学 随机的
上一篇:如何找到矩形內每個點的距離?
