Function Random returns numbers larger than those defined

Asked

Viewed 186 times

-1

I made a function that should return a number random between 0 and 50, but is returning numbers greater than 50.

function random(){
    var random = Math.random(0, 50)
    var resultado = random * 100
    alert(parseInt(resultado))
}

1 answer

6


The function Math.random() returns a pseudo-random number in the range [0, 1[ MDN - Math.Andom

This interval corresponds to the same 0 <= Math.random() < 1, i.e., this function returns from zero (including zero) to a real number less than 1.

Examples of numbers returned in the function Math.random():

0.9846826303988312
0.2173987016086012
0.30711801525592763
0.00979063791034318
0.6827624772816574

To obtain a greater number than those returned by Math.random(), the return of this method must be multiplied by a natural number greater than 1.

Math.random() * 50

Results:

32.593616844490846
1.3650244020898872
49.12502614593396
8.921204790246563
19.29410180999559

If you want to get an integer you use the method Math.round() .

The function Math.round()returns the value of a number rounded to the nearest integer. MDN - Math.round

Math.round(Math.random() * 50)

Results:

8
13
48
29
40

Solving the problem:

What you must do to solve your problem is to remove the parameters of the Math.random() and multiply by 50 instead of 100, this way will only return numbers less than 50, soon after, uses Math.round() to round value and allow a range of 0 to 50.

function random() {
    var random = Math.random() * 50;
    return Math.round(random);
}

alert(random());

  • 3

    With floor will never reach 50. And it would be better that function returned the number, no?

  • 1

    I fixed it using round.

  • 1

    Put the two codes(floor and round) and explain the differences, why one works with open right interval and the other code works with closed right interval. Will add more value to answer. Random variable is unnecessary.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.