How to calculate a random number between any values?

Source: Internet
Author: User

Do you know how to calculate a random number ranging from 1 to 10? Let me know,

First, the math. Random () method is used to calculate a random number and return a random number greater than or equal to 0 and less than 1,

Math. random () * 10 isn't it true that the return value is greater than or equal to 0 and less than 10, but he can only return a number smaller than 10, and cannot return 10? What should I do, we add 1 to the original function and it becomes math. random () * 10 + 1; now we can return a random number ranging from 1 to 10, but we return many decimal places, which do not meet the requirements. Math is used below. floor () Is the function, which is rounded down, that is, 10.99 passes through math. all floors are 10, math. ceil (rounded up) returns 11 even if it is 10.00001. Now we can find out the result, math. floor (math. random () * 10 + 1); then the result can be obtained;

What about the functions between 2 and 10? Directly code math. Floor (math. Random () * 9 + 2 );

So what about 3 to 11 and 4 to 88? Every time this is done, it is not a solution. Next we will introduce a general method;

 

Function selectfrom (lowvalue, highvalue ){

VaR choice = highvalue-lowvalue + 1;

Return math. Floor (math. Random () * Choice + lowvalue );

}

Then, directly adjust the above method to OK;

The previous blog is too rough. I'm lucky to give some advice from a garden friend. I will write the naming rules for the future. You are welcome to leave a message to discuss Js.

How to calculate a random number between any values?

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.