iPhone: random() function gives me the same random number everytime

前端 未结 8 2138
情书的邮戳
情书的邮戳 2020-12-09 14:02

I am using function random()%x for the generation of a random number, but every time I start the application I see that it creates or generates the same number.

Lik

8条回答
  •  庸人自扰
    2020-12-09 14:14

    For newbies that come across this post:

    The random() function produces a pseudo-random sequence. random() ways gives you the same pseudo-random sequence each time you use it. You need to "seed" the sequence to pick a different starting point so each time you run it so it appears different. You can use the system time to seed (srandom(time(NULL)) or use the helper function srandomdev().

    To experiment try:

    #include "stdio.h"
    
    int main(void) {
        int i;
        for (i = 0; i < 10; i++)
            printf("%d\n", random());
    
        return 0;
    }
    

    You'll always get the same sequence, on my computer it gives:

    1804289383
    846930886
    1681692777
    1714636915
    1957747793
    424238335
    719885386
    1649760492
    596516649
    1189641421
    

    More reading:

    • The random man page for more information. (Run man random from Terminal.)

提交回复
热议问题