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

前端 未结 8 2121
情书的邮戳
情书的邮戳 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条回答
  •  Happy的楠姐
    2020-12-09 14:17

    In your application delegate:

    - (void) applicationDidFinishLaunching:(UIApplication *)application 
    {
        srandom(time(NULL));
    
        // ...
    
        for (int i = 0; i < 100; i++) {
          NSLog(@"%d", random());
        }
    }
    

    The reason this works is because pseudorandom number generators require a starting, or seed value. By using the time, you are more likely to get different sequences of "random" numbers upon each execution.

    If you do not specify a seed value, the same seed is used on each execution, which yields the same sequence. This is usually undesired behavior, but in some cases it is useful to be able to generate the same sequence, for example, for testing algorithms.

    In most cases, you will want to specify a seed value that will change between runs, which is where the current time comes in handy.

提交回复
热议问题