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
464 views
in Technique[技术] by (71.8m points)

c - Problems when calling srand(time(NULL)) inside rollDice function

When I used at first srand(time(NULL)) in rollDice() function it did not work. But when I put it in main, it works. Why is that? Can you tell me the logic?

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int rollDice(void) {
    return (1+rand()%6) + (1+rand()%6);
}
int main(void) {
    int roll;
    srand(time(NULL));          
    roll = rollDice();
    printf("You rolled %d.
", roll);

    enum Gamestatus {WON,LOST,CONTINUE};
    enum Gamestatus status;

    while(status==CONTINUE){
        printf("You are rolling again: 
");
        printf("You rolled %d
", roll = rollDice());

        if (targetPoint==roll){
            printf("You win!");
            status=WON;
        }
        else if(7==roll){
            printf("You lost!");
            status=LOST;
        }
        else
            status=CONTINUE;
    }
    return 0;
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Let's say you have millions of books with rows upon rows of random numbers. Before you get a random number you need to select a book.

After you have a book, to get random numbers, read numbers sequentially from the book. Changing the book gets another sequence of random numbers.
Changing to the same book restarts the sequence form the first number in the book.

srand() chooses a book and starts random numbers from the beginning
rand() reads the next number from the selected book

If you put srand() inside the loop, you are effectively restarting the random number sequence from the beginning of the same book.

Solution: select 1 book once, and keep reading numbers from it for ever and ever.

In a C program, if you don't "select a book", the random numbers come from book #1 or, in other words, in the absence of a srand() call, the function rand() behaves as if srand(1) has been called.


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

...