Order of operations for Math.floor(Math.random() * 5 + 1)?

时间:2015-12-10 01:53:11

标签: javascript math operator-precedence

In the Code Academy JS course, Dragon Slayer 2/6, the following text is used in the hint to describe the order of operations for the code I included in the title.

How does this code work?

Math.floor(Math.random() * 5 + 1);

  • First we use Math.random() to create a random number from 0 up to 1. For example, 0.5

  • Then we multiply by 5 to make the random number from 0 up to 5. For >example, 0.5 * 5 = 2.5

  • Next we use Math.floor() to round down to a whole number. For example, >Math.floor( 2.5 ) = 2

  • Finally we add 1 to change the range from between 0 and 4 to between 1 and >5 (up to and including 5)

I've looked this up in several different places (here and here), and a majority of them either focus on the range that Math.random() produces (which I understand) or confirm the order of operations outlined in the hint, wherein "Math.floor" acts upon "Math.random()*5" prior to the "+1" being added.

It seems to me however that, according to the order of operations that I learned in school, the last two steps should be flipped. Would that not be the case since "Math.random()*5" and the "+ 1" are both within the parenthesis?

While the difference between these two might not make a difference in the value returned from this particular code, I could see a fundamental change in the order of operation like the one outlined here would cause me some frustration further down the road if I didn't know it.

4 个答案:

答案 0 :(得分:6)

Math.floor() will work on whatever is inside the brackets, after it has been calculated.

Math.floor(Math.random() * 5 + 1)

is the same as

var i = Math.random() * 5;
i += 1;
Math.floor(i);

答案 1 :(得分:4)

You are correct that the wording on the page is wrong. The last thing that will happen is the floor call. Everything in the parenthesis will be processed first.

答案 2 :(得分:2)

Honestly, I think they mixed up here, and you're right. According to PEMDAS and any mathematics I've ever learned, the +1 comes before the Math.floor function.

答案 3 :(得分:0)

Math.random()函数返回范围[0,1)中的随机数,即从0(包括)到最多但不包括1(不包括)。它可以是0,.34,.42等任何东西。 如果你想要0-5之间的随机数。 你将使用Math.Random()* 5。这将给你任何数字,如0,4.43.4.34但不是五。 然后我们添加1像这样的Math.random()* 5 + 1.现在你可能会得到一个介于0和6之间的数字。但是你不希望数字超过5。所以 你应用floor方法,它将返回小于或等于给定数字的最大整数。

相关问题