【问题标题】:var damage = Math.max(Math.floor(Math.random() * max)+1, min) what is the meaning first 'Math.max' and last ',min' herevar damage = Math.max(Math.floor(Math.random() * max)+1, min) 第一个 'Math.max' 和最后一个 ',min' 是什么意思
【发布时间】:2019-08-28 13:20:32
【问题描述】:
var damage = Math.max(Math.floor(Math.random() * max)+1, min); 

这里第一个Math.max和最后一个,min是什么意思。请解释整行。

【问题讨论】:

  • Math.max 记录在 heremin 是您想要的最小结果的数字,max 是您想要的最大值 - Math.random 记录在 here 和Math.floor 记录在here - 所以damage 将是minmax 之间的随机整数值
  • 取决于min 的值,这会导致随机数偏向min - 因此,如果min 为10 且max20,则不是理想的随机函数例如...返回的值的一半是 10,另一半分布在 10 到 20 之间
  • 更好的随机函数是Math.floor(Math.random() * (max - min + 1)) + min

标签: javascript random numbers


【解决方案1】:

如果您在MDN 查找Math.random

Math.random() 函数返回一个浮点伪随机数 0-1 范围内的数字(包括 0,但不包括 1),大约 在该范围内均匀分布 - 然后您可以扩展到 您想要的范围

因此,这里的范围是max,您将取表达式Math.random() * maxMath.floor,然后将其加1。

Math.floor 会将产生的数字四舍五入为小于或等于给定结果的最大整数。因此,如果Math.random() * max 的结果是5.95,则Math.floor 将使结果数字为5

最后我们找到上一步的结果数和min变量中的最大值,并将结果分配给damage变量。

【讨论】:

    【解决方案2】:

    Math 是 javascript 中的内置对象,它具有方法和属性,这里 [Math.max][2] 用于查找最大的数字。 Math.floor & Math.random 也是可用的方法

    为了便于理解,我把代码分成了多行

    function findMax(max, min) {
      let findRandom = Math.random() * max; // generate a random number
      // if it is a decimal number get the previous whole number
      let findLower = Math.floor(findRandom);
      // add one with the generated whole number
      let addOne = findLower + 1;
      // find the maximum between two numbers, one is generated & another is 
      // supplied as argument
      let damage = Math.max(addOne, min)
      return damage;
    }
    console.log(findMax(4, 1))

    【讨论】:

      【解决方案3】:

      Math.max 是一个函数,当传递可变数量的数字时,返回最大的数字:

      console.log(Math.max(1, 2, 3));

      您的代码中的mindamage 可以是的最小数字 - 所以它的工作原理是(伪代码):

      set damage to the maximum number out of:
          A random number between 0 and 1, multiplied by max, rounded down,
          or min;
      

      【讨论】:

        猜你喜欢
        • 2020-11-08
        • 1970-01-01
        • 2016-06-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-26
        • 1970-01-01
        • 2023-03-19
        相关资源
        最近更新 更多