How to use Math. floor and Math. random to obtain random Integers

Source: Internet
Author: User

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

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

So we can use Math. floor (Math. random () to obtain an integer in the range you want.
For example, from 1 ~ Take a random number within 52:
First Math. random () * 52 // so that we can get a number with a value greater than or equal to 0 and less than 52.
Then add 1: Math. random () * 52 + 1 // now the number is greater than or equal to 1 and <53
Then use Math. floor to get the integer

Final: Math. floor (Math. random () * 52 + 1)

The value range is 1 ~ The random integer of 52.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.