Why do I get the same result with rand() every time I compile and run?

后端 未结 4 659
陌清茗
陌清茗 2020-11-27 07:47

Whenever I run this code, I get a same result.

Program

#include

int main(int agrc, const char *argv[]) {
 int i = rand();
 printf(\"         


        
相关标签:
4条回答
  • 2020-11-27 08:19

    You want to initialize the PRNG.

    Initialize it once (typically inside main()) with a call to the srand() function.

    If you do not initialize the PRNG, the default is to have it initialized with the value 1. Of course initializing it with some other constant value will not give you different pseudo random numbers for different runs of the program.

    srand(1); /* same as default */
    srand(42); /* no gain, compared to the line above */
    

    You need to initialize with a value that changes with each run of the program. The value returned from the time() function is the value most often used.

    srand(time(NULL)); /* different pseudo random numbers almost every run */
    

    The problem with time(NULL) is that it returns the same value at the same second. So, if you call your program twice at 11:35:17 of the same day you will get the same pseudo random numbers.

    0 讨论(0)
  • 2020-11-27 08:33

    Just to add to Yacoby's answer - I was slightly surprised that it didn't default to a time-based seed, so I looked up the man page:

    If no seed value is provided, the rand() function is automatically seeded with a value of 1.

    So if you change your code to use seed(1) you should still see the same output - but seed(time()) will make it change each time.

    0 讨论(0)
  • 2020-11-27 08:39

    You need to seed the rand function with a unique number before it can be used. The easiest method is to use time()

    For example

    srand(time(NULL));
    rand();//now returns a random number
    

    The reason is that the random numbers provided by rand() (or any other algorithm based function) aren't random. The rand function just takes its current numerical state, applies a transformation, saves the result of the transformation as the new state and returns the new state.

    So to get rand to return different pseudo random numbers, you first have to set the state of rand() to something unique.

    0 讨论(0)
  • 2020-11-27 08:43

    The output from rand is pseudo-random, which means that it looks effectively random, but is computed the same way each time, starting from a special value called the seed. With the same seed value, you get the same sequence of random numbers.

    To set a different seed, use the standard C function void srand(unsigned int) once in your code before you start generating random numbers. One common way of getting a different sequence of random numbers each time you run the program is to base the seed on the clock time. E.g. srand(clock())

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