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

c - calling rand() returning non-random results

I am writing a simple C program that tosses a coin 100000 times and calculates how many heads and how many tails resulted from the toss using srand and rand. Here is what I have:

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

int main(void){

    int i;
    int h=0;
    int t=0;
    int n;

    for(i=0;i<100000;i++){
        srand(time(NULL));
        n=rand()%2;
        if(n==0){
            h++;
        }
        else {   
            t++;
        }
    }

    printf("%d heads
", h);
    printf("%d tails
", t);

    return EXIT_SUCCESS;
}

However when running the program I sometimes get 100000 heads and 0 tails and sometimes 0 heads and 100000 tails and sometimes I get random numbers in heads and tails but not in any way a 50% heads 50% tails.

Am I missing something? Thanks!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You are seeding the pseudo-random number generator with the same seed each time around the look. Simply move the call to srand outside the loop.

srand(time(NULL));
for(i=0;i<100000;i++){
    n=rand()%2;
    .....

A pseudo-random number generator (PRNG) is deterministic. That is, given the same initial seed, it will return the same sequence of numbers each time is is called. In your code, since you seed every time you call rand, you get the same sequence of 1 number for every iteration of your loop. Now, different executions of the program will have different results, because time will have changed.

And in the cases when you were not seeing 100% heads or 100% tails, that would be when the loop took sufficiently long for time to have advanced.


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

...