How can I generate different random numbers for each player?

后端 未结 3 1384
轮回少年
轮回少年 2020-12-12 08:12

Both players get the same random number! ّI want each player to get a different number since they are throwing dice. here is the code:

#include 

        
相关标签:
3条回答
  • 2020-12-12 08:40

    srand ( time(NULL) ); is used to seed the pseudo-random number generator. time() having a granularity of 1 second, if you seed the PNRG every time you call the roll_a_dice() function, for all the calls made within the granularity period, rand() will end up returning the same random number.

    Move the srand ( time(NULL) ); out of the roll_a_dice() function, call that only once in main().

    0 讨论(0)
  • 2020-12-12 08:40

    You only need to seed once. Move srand to the top of main and it will work.

    0 讨论(0)
  • 2020-12-12 08:53

    srand( int ); is used to initialize a seed. From there each time you call rand() you'll get a new random value. By calling srand() in roll_a_dice() you keep reseting the seed every time. Just move srand() at the start of your main().

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