A method of generating random numbers in objective-c _ios

Source: Internet
Author: User

This paper briefly introduces several common methods of generating random numbers in objective-c, and shares them with us, hoping to bring some reference value to everyone. Specifically as follows:

1), Arc4random () method : More accurate does not need to generate the immediately seed

Use the following methods:

The code for obtaining integers between 0 and x-1 via Arc4random () is as follows:

 int value = Arc4random ()% x;

The code to get an integer between 1 and X is as follows:

 int value = (arc4random ()% x) + 1;

2), Ccrandom_0_1 () method : used in cocos2d , range is [0,1]

Use the following methods:

 float random = ccrandom_0_1 () * 5; [0,5]  ccrandom_0_1 () value range is [0,1]

3), Random () method : The seed should be set when initializing

Use the following methods:

Srandom ((unsigned int) time (time_t *) NULL); When initializing, set the seed.

The code in the article is available in a more detailed note, I believe it is not difficult to understand. Interested friends can test their own hands.

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.