How can I generate different random numbers for each player?

不问归期 提交于 2019-11-27 19:44:05

问题


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 <stdlib.h>
#include <stdio.h>
#include <time.h>

int roll_a_dice(void);

int main(int argc, const char *argv[])
{   
    int flag;
    int answer1 = roll_a_dice();
    int answer2 = roll_a_dice();

    printf("Die 1 (rolled by player 1): %d\n", answer1);
    printf("Die 2 (rolled by player 2): %d\n", answer2);

    if (answer1>answer2) {
        printf("Player 1 is starting!\n");
        flag = 1;
    } else {
        printf("Player 2 is starting!\n");
        flag = 2;
    }

    printf("Goodbye!\n");

    return 0;        
}

int roll_a_dice(void)
{
    int r;

    srand(time(NULL));
    r = 1 + rand() % 6;

    return r;
}

The players are throwing dice. So number has to be 1-6. How can I fix this?


回答1:


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().




回答2:


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




回答3:


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().



来源:https://stackoverflow.com/questions/36558716/how-can-i-generate-different-random-numbers-for-each-player

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!