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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…