Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

c - How can I generate different random numbers for each player?

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
", answer1);
    printf("Die 2 (rolled by player 2): %d
", answer2);

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

    printf("Goodbye!
");

    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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...