Home > Web Front-end > JS Tutorial > Detailed explanation of how to use Math.floor and Math.random to get random integers_Basic knowledge

Detailed explanation of how to use Math.floor and Math.random to get random integers_Basic knowledge

WBOY
Release: 2016-05-16 17:34:29
Original
1945 people have browsed it

Math.random(): Get 0~1 random number

Math.floor() method rounds a number DOWNWARDS to the nearest integer, and returns the result. (less than or equal to x, and the integer closest to x.)
In fact, the return value is the integer digit of the number:
Math.floor(0.666) --> 0
Math.floor(39.2783) --> 39

So we can use Math.floor(Math.random()) to get the integer in a range you want.
For example: Now we want to pick a random number from 1 to 52:
First Math.random()*52 //In this way we can get a number with >=0 and <52
Then Add 1: Math.random()*52 1 //Now this number is >=1 and <53
and then use Math.floor to round

Finally: Math.floor(Math.random()*52 1)

This will give you a random integer with a value ranging from 1 to 52.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template