【问题标题】:What exactly does Math.floor do?Math.floor 到底是做什么的?
【发布时间】:2016-07-06 06:29:01
【问题描述】:

我了解Math.floor 会舍入到最接近的整数,例如

function myFunction() {
    document.getElementById("demo").innerHTML = Math.floor(0.9);
}

将输出1

但我不明白为什么

function myFunction() {
    document.getElementById("demo").innerHTML = Math.floor(Math.random()*2);
}

输出1

谢谢。

【问题讨论】:

  • 它不会四舍五入到最接近的整数。它删除浮点数的任何小数部分;实际上它总是向零舍入。 Math.floor(1.9999999)1Math.floor(0.9)0,而不是 1;你在浏览器的开发者控制台中试过了吗?
  • RTFM
  • 如果您已经投反对票,请解释原因..
  • 投反对票,因为所有有问题的陈述都不正确,如果您阅读手册了解 Math.floor 的实际作用,这就是简单的数学运算

标签: javascript math random


【解决方案1】:

不,实际上这行代码输出0

 Math.floor(0.9);

Math.floor 总是四舍五入到小于您输入的最接近的整数。您可能会将其与Math.round 混淆,后者会舍入到最近的 个整数。

这就是为什么这段代码总是输出10,因为输入永远不会达到2 或更大:

Math.floor(Math.random()*2)

在 JavaScript 中实际上有三种不同的舍入函数:Math.floor,它的相反 Math.ceil 和“通常的”Math.round

这些工作如下:

Math.floor(0.1); // Outputs 0
Math.ceil(0.1); // Outputs 1
Math.round(0.1); // Outputs 0

Math.floor(0.9); // Outputs 0
Math.ceil(0.9); // Outputs 1
Math.round(0.9); // Outputs 1

Math.floor(0.5); // Outputs 0
Math.ceil(0.5); // Outputs 1
Math.round(0.5); // Outputs 1

【讨论】:

  • 谢谢伙计,所以 Math.ceil(2.3) 会输出 3?
  • 非常感谢,懂的朋友
【解决方案2】:

floor() 方法将数字向下舍入到最接近的整数, 并返回结果。

如果传递的参数是整数,则该值不会被四舍五入。

【讨论】:

    【解决方案3】:

    正如其他人所解释的,floor() 总是将 向下 舍入为整数,而不是 最接近的 整数。

    在回答您问题的另一部分时,random() 默认返回一个介于 0 和 1 之间的数字。因此,floor(random()) 将始终返回零。 floor(random()*2) 将返回 1 一半的时间(当 random() 给出 0.5 或更高的结果时,使其在 *2 之后一个或多个)和 0 的另一半时间(当 random() 给出更低的结果时比 0.5,所以乘以 2 仍然小于 1。)。

    【讨论】:

      【解决方案4】:

      0 Math.random()

      Math.floor(input) = max(x, x 是整数,x

      所以,让我们看看结果

      0

      2 * 0

      0

      因此,Math.floor(2 * Math.random()) = {0; 1}

      编辑:

      Math.floor 向下舍入。

      【讨论】:

        【解决方案5】:

        var x = Math.floor(.9);
        $("body").append(x);
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-08-06
          • 2013-09-02
          • 2014-01-02
          • 2013-10-10
          • 2017-05-08
          • 2022-01-20
          • 2012-10-17
          • 2017-06-15
          相关资源
          最近更新 更多