Random Number generated in IOS

Source: Internet
Author: User
Tags random seed

Address: http://www.cnblogs.com/zeejun/archive/2012/07/22/2603329.html

IOS has the following three random number methods:

1. srand (unsigned) time (0); // the random number generated each time the sentence is not added
Int I = rand () % 5;

2. srandom (time (0 ));
Int I = random () % 5;

3. Int I = arc4random () % 5;

 

Note: rand () and random () are not real pseudo-random number generators. before using them, initialize random seeds. Otherwise, the random numbers generated each time are the same.

Arc4random () is a real pseudo-randomAlgorithm, Do not need to generate random seed, because it is automatically generated during the first call. And the range is twice that of rand. In the iPhone, rand_max is 0x7fffffff (2147483647), while the maximum value returned by arc4random () is 0x100000000 (4294967296 ).

Precision comparison: arc4random ()> random ()> rand ().

 

Common method: arc4random

 

1,Obtain a random integer in the following range:[0,100)Including0, Not including100

IntX = arc4random () % 100;

2,The range for obtaining a random number is:[,), Including500, Not including1000

IntY = (arc4random () % 501) + 500;

3,Returns a random integer in the range[From,), IncludingFrom, Not includingTo

-(INT) getrandomnumber :( INT) from to :( INT)

{

Return (INT) (from + (arc4random () % (to-from + 1 )));

}

 

Refer:

1. http://kb.cnblogs.com/a/2335710/

2. http://mmz06.blog.163.com/blog/static/121416962011101103734767/

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.