rand() not generating random numbers after modulo operation

后端 未结 8 2039
一向
一向 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 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));

提交回复
热议问题