rand() not generating random numbers after modulo operation

后端 未结 8 2015
一向
一向 2020-12-07 04:43

I\'m taking a C refresher and took on a board game as an exercise. The board game is \"Game of the Generals\" and is pretty much like chess as it uses pieces with ranks on a

相关标签:
8条回答
  • 2020-12-07 04:44

    Random number generator must be initialized with random seed. See srand() function. Often it initialized with time: srand(time(NULL)).

    0 讨论(0)
  • 2020-12-07 04:46

    you should use srand() to seed your random generator.

    A common random seeding is srand ( time(NULL) );

    0 讨论(0)
  • 2020-12-07 04:51

    Yes, because you dind't "initialize" the rand(). Try to do something like that srand (time(NULL)) ;

    You have also to include time.h

    0 讨论(0)
  • 2020-12-07 04:53

    All answers are correct, you need to seed the rand function with something like

    srand(time(NULL));
    

    But why?

    ´rand´ is a so called pseudo random number generator. That means that the numbers are not really random, but the function uses an algorithm that produces a sequence of numbers that have similar characteristics to random numbers, especially concerning uniform distribution.

    This means that when using the same seed, the same sequence will be produced. This is why those generators are also called deterministic random number generators.

    Seeding it will provide a different start value and therefore result in different number sequences.

    0 讨论(0)
  • 2020-12-07 05:06

    You need to realize that rand() is a pseudorandom number generator, and it is specifically engineered to return the same sequence of numbers for a given seed. The seed is set with the srand() function.

    srand(0);
    printf("the first rand() with seed 0 is %d\n", rand());
    srand(1);
    printf("the first rand() with seed 1 is %d\n", rand());
    srand(0);
    printf("the first rand() with seed 0 is still %d\n", rand());
    

    So, the way to make it less predictable is generally to re-seed it from something a bit more random, or at least from something that is not the same every time you run the program:

    srand(time(NULL));

    0 讨论(0)
  • 2020-12-07 05:07

    Call this once:

    srand (time(NULL));
    

    to initialise before calling rand()

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