Exit
  • Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
  • 한국 커뮤니티
0

I don't understand this code example with Math.random()

Community Beginner ,
Apr 10, 2019 Apr 10, 2019

import flash.events.MouseEvent;

stop();

var x:int=0;

var y:int=0;

addEventListener(MouseEvent.CLICK,startMove);

function startMove(m:MouseEvent){

x=int(Math.random()*10-5);

y=int(Math.random()*10-5);

removeEventListener(MouseEvent.CLICK,startMove);

addEventListener(MouseEvent.CLICK,stopMove);

addEventListener(Event.ENTER_FRAME,moveMe);

}

dx=int(Math.random()*10-5);

     What does the 10 and the 5 represent? How do I make it a minimum of one number and a maximum of another?

270
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines

correct answers 1 Correct answer

Community Expert , Apr 10, 2019 Apr 10, 2019

Hi.

Math.random() returns a number from 0 to 1. So:

- If Math.random() returns 0, than 0 * 10 - 5 = -5;

- If Math.random() returns 1, than 1 * 10 - 5 = 5.

This means you're gonna get a floating-point number in a range from -5 to 5. -5 being the minimum value and 5 the maximum value.

As the result is being rounded using the int class, you get the closest integer that is less than or equal to the specified number or expression. With this being said, the results are:

-4, -3, -2, -1, 0, 1, 2, 3, 4

If you w

...
Translate
Community Expert ,
Apr 10, 2019 Apr 10, 2019
LATEST

Hi.

Math.random() returns a number from 0 to 1. So:

- If Math.random() returns 0, than 0 * 10 - 5 = -5;

- If Math.random() returns 1, than 1 * 10 - 5 = 5.

This means you're gonna get a floating-point number in a range from -5 to 5. -5 being the minimum value and 5 the maximum value.

As the result is being rounded using the int class, you get the closest integer that is less than or equal to the specified number or expression. With this being said, the results are:

-4, -3, -2, -1, 0, 1, 2, 3, 4

If you want to include -5 and 5, use Math.round() instead of int().

I hope this makes sense.

Regards,

JC

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines