如果你想在
min(含)到
max(含)之间找一个随机整数,你可以使用下面的公式:
Math.floor(Math.random() * (max-min + 1)) + min
示例: 两个数字之间的整数值
// input from the user const min = parseInt(prompt("Enter a min value: ")); const max = parseInt(prompt("Enter a max value: ")); // generating a random number const a = Math.floor(Math.random() * (max-min + 1)) + min; // display a random number console.log(`Random value between ${min} and ${max} is ${a}`);
输出
Enter a min value: 1 Enter a min value: 50 Random value between 1 and 50 is 47
在 JavaScript 中,您可以使用
Math.random()
函数生成随机数。
Math.random()
返回一个随机浮点数,范围从 0 到小于 1(包括 0 且不包括 1)
上述程序将显示min(含)到max(含)之间的整数输出。
首先,将最小值和最大值作为用户的输入。然后使用
Math.random()
方法从传入的值中获取随机数。
Math.floor()
返回最接近的整数值。