生成随机数的一段代码。引来一片嘘嘘,删掉了一句,呵呵,顶不住了。可是我觉得够用就行了为原则。
改进一下,提高种子的精度,完了引入os的radom设备
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
void init_random()
{
unsigned int ticks;
struct timeval tv;
gettimeofday(&tv,NULL);
ticks = tv.tv_sec + tv.tv_usec;
srand(ticks);
}
//ibuflen---需要生成的随即串的长度
int genrandstr(char* pszbuf,int ibuflen)
{
static const char sourchar[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
init_random();
for(int i=0;i<ibuflen;i++)
{
int x = rand()/(RAND_MAX/(sizeof(sourchar)-1));
pszbuf[i] = sourchar[x];
}
pszbuf[ibuflen] = '\0';
}
int main(int argc, char* argv[])
{
printf("begin randstr...,RAND_MAX=%d\n",RAND_MAX);
char buf[9] = {0};
genrandstr(buf,8);
printf("randstr=%s\n",buf);
genrandstr(buf,8);
printf("randstr=%s\n",buf);
genrandstr(buf,8);
printf("randstr=%s\n",buf);
genrandstr(buf,8);
printf("randstr=%s\n",buf);
genrandstr(buf,8);
printf("randstr=%s\n",buf);
genrandstr(buf,8);
printf("randstr=%s\n",buf);
printf("end randstr...\n");
return 0;
}