您需要srand
main 中的函数。
随时间播种:
#include <time.h> //header for time
int main(){
srand(time(NULL)); // call only once and preferably at the start of main
// your code including the function randBit()
return 0;
}
这是一个示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int randBit()
{
int bit;
double randval;
randval = (double)rand()/(double)RAND_MAX;
if(randval<0.5) bit=0;
else bit=1;
return bit;
}
int main(){
srand(time(NULL));
int i=0,random=0;
for(i=0;i<100;i++){
random = randBit();
printf("%d ",random);
}
printf("\n");
return 0;
}
这是输出:
Notra:Desktop Sukhvir$ ./test
1 1 0 0 1 1 0 1 0 0 1 0 0 1 1 0 1 1 0 1 1 0 0 0 0 1 0 1 0 1 1 0 1 1 0 1 0 0 0 1 0 0 1 1 1 1 0 1 0 0 0 1 1 1 0 0 0 1 0 1 1 1 0 0 1 0 1 1 1 0 0 0 1 0 1 0 1 0 1 1 1 1 0 1 1 0 0 0 1 0 1 1 0 0 1 0 1 1 0 1