用js如何得到10-30的随机数用Mathround取整
以下是用JavaScript代码实现得到10-30的随机数,并用Math.round()进行取整的方法:
var randomNum = Math.floor(Math.random() * 21) + 10;
// 生成0到20之间的随机数,再加上10,得到10到30之间的随机数
var roundedNum = Math.round(randomNum);
// 使用Math.round()进行四舍五入取整
console.log(roundedNum);
解释:Math.random()方法会生成一个0到1之间的随机数,乘以21得到0到20之间的随机数,再加上10得到10到30之间的随机数。然后使用Math.round()方法进行四舍五入取整,最终得到一个10到30之间的整数。
原文地址: https://www.cveoy.top/t/topic/bhWd 著作权归作者所有。请勿转载和采集!