rand with seed does not return random if function looped

前端 未结 5 843
滥情空心
滥情空心 2020-12-17 21:19

I wrote this C code below, when I loop, it returns a random number. How can I achieve the 5 different random values if myrand() is executed?

#include 

        
相关标签:
5条回答
  • 2020-12-17 21:45

    Seeding the generator should be done once(for each sequence of random numbers you want to generate of course!):

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        int seed = time(NULL);
        srand(seed);
        int value = 0;
        int i=0;
        for (i=0; i< 5; i++)
        {
            value =rand();
            printf("value is %d\n", value);
        }
    }
    
    0 讨论(0)
  • 2020-12-17 21:45

    Move the srand() call into main(), before the loop.

    In other words, call srand() once and then call rand() repeatedly, without any further calls to srand():

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        int value = 0;
        int i = 0;
        srand(time(NULL));
        for (i = 0; i < 5; i++)
        {
            value = rand();
            printf("value is %d\n", value);
        }
    }
    
    0 讨论(0)
  • 2020-12-17 21:46

    If you want to reseed (for extra randomness) every time you call random(), here's one way you could do that:

    srandom( time(0)+clock()+random() );
    
    • time() updates once per second, but will be different every time you run your program
    • clock() updates much more frequently, but starts at 0 every time you run your program
    • random() makes sure that you (usually) don't reseed with the same value twice in a row if your loop is faster than the granularity of clock()

    Of course you could do more if you really, really, want randomness -- but this is a start.

    0 讨论(0)
  • 2020-12-17 21:47

    The point of seed() is to start the sequence of random numbers with a known value,
    you will then always get the same sequence of numbers given the same seed.

    This is why you have seed(), it both allows you to generate the same sequence for testing, or given a random seed (typically the time) you get a different sequence each time

    0 讨论(0)
  • 2020-12-17 21:48

    Try this:

    #include <stdio.h>
    #include <time.h>
    int main(void) {
        for (int i = 0; i < 10; i++) {
            printf("%ld\n", (long)time(NULL));
        }
    }
    

    My "guess" is that 10 equal values will be printed :)

    0 讨论(0)
提交回复
热议问题