Math.floor究竟做了什么?

时间:2016-03-19 13:31:22

标签: javascript math random

我理解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

感谢。

5 个答案:

答案 0 :(得分:2)

  

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

     

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

答案 1 :(得分:2)

不,实际上这行代码输出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

答案 2 :(得分:1)

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

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

答案 3 :(得分:1)

0< = Math.random()< 1

Math.floor(输入)= max(x,其中x是整数,x <=输入)

因此,让我们看看结果

0&lt; = Math.random()&lt; 1

2 * 0&lt; = 2 * Math.random()&lt; 2 * 1

0&lt; = 2 * Math.random()&lt; 2

结果,Math.floor(2 * Math.random())= {0; 1}

编辑:

Math.floor向下舍入。

答案 4 :(得分:0)

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