【问题标题】:Math.random() and Math.floor() why are they used together? [closed]Math.random() 和 Math.floor() 为什么要一起使用? [关闭]
【发布时间】:2025-12-10 09:05:02
【问题描述】:

也有可能生成的数字在 30 到 90 之间。或者它只是在 0 到 n 之间生成?

【问题讨论】:

  • “一起使用”是什么意思?
  • 标题和问题不相关。你也知道怎么加30吗?
  • Math.random() 返回一个介于 0 和 1 之间的浮点数。Math.floor() 将截断该数字(例如:Math.floor(1.45); // returns 1)。

标签: javascript function


【解决方案1】:
// Returns a random integer between min and max
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

来自Mozilla Developer Network

【讨论】:

  • (max - min + 1) 似乎是错误的。不应该只是(max - min)吗?
【解决方案2】:

生成 0 到 60 之间的数字(您似乎知道它是如何工作的),然后加上 30。

【讨论】:

    最近更新 更多