Rand () doesn't seem so random

This is how I create an int:

int randNumber = rand() % 4;
NSLog(@"%d", randNumber);

However, every time I run the application, the number is the same no matter what.

I created a button and applied an action to it that reinitializes a random number and writes a new number, and then generates a random number, but when starting the application, the random number is always the same (I ran it more than 20 times).

Any idea why the random number is always the same when starting the application?

+3
source share
4 answers

Try using arc4random()one that doesn't require seed

+13
source

, . , . . , .

: Objective-C

+3

rand () is a pseudo random number generator. he uses seeds and produces an even sequence for each seed.

If you do this at the beginning of the program

srand(time(NULL));

Will work

+1
source

You need to call srand (unsigned int seed); for the seed of the rand function. If you do not name srand, it will be sown 1 time.

0
source

All Articles