microsoft / pxt

Microsoft MakeCode (PXT - Programming eXperience Toolkit)
https://makecode.com
MIT License
2.1k stars 584 forks source link

When picked random numbers, an extra "1" was added up in Javascript #2375

Closed WendyFeng01 closed 7 years ago

WendyFeng01 commented 7 years ago

Repro steps:

Issue1:

• Navigate to https://makecode.microbit.org/ • Drag "pick random" block such as random • Switch to JAVASCRIPT

Expected result: Javascript code should like this: basic.showNumber(Math.random(0 + 1)) Actual result: javascript1

Issue2:

• Drag "pick random" block such as random02

Expected result: Javascript code should like this: roll = Math.random(4) Actual result: javascr

guillaumejenkins commented 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!

lock[bot] commented 5 years ago

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.