Closed WendyFeng01 closed 7 years ago
TL;DR: this is by design, because Math.random()
is exclusive in JS, but inclusive in Blocks.
In JS, the argument in Math.random()
is exclusive - meaning Math.random(5)
returns a number between 0 and 4. In Blocks, to avoid confusing kids, we decided to make the number inclusive. So, in JS, the argument will always be 1 higher than the argument in the Blocks.
When the argument is a number, we can simply change it by 1 (4 in Blocks becomes 5 in JS, and vice versa). When the argument is an expression (such as 0 + 1
), we cannot as easily modify a value directly, because the expression could be adding 2 variables together (e.g. Math.random(foo + bar)
). So, in the case of an expression, we append a + 1
to it in JS, while in Blocks the expression remains unchanged.
Hopefully this clarifies things!
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Repro steps:
Issue1:
• Navigate to https://makecode.microbit.org/ • Drag "pick random" block such as • Switch to JAVASCRIPT
Expected result: Javascript code should like this: basic.showNumber(Math.random(0 + 1)) Actual result:
Issue2:
• Drag "pick random" block such as
Expected result: Javascript code should like this: roll = Math.random(4) Actual result: