随机数生成算法,每一次生成都不一样

来源:互联网 发布:u盘照片数据恢复 编辑:程序博客网 时间:2024/05/18 01:07

项目中要用到一个随机数生成算法,但是每一次生成间隔时间很短,还要保证每一次生成的随机数都不相同,于是就想到了利用当前时间的毫秒作为随机数种子来生成。

#include <iostream>#include <sys/time.h> // for gettimeofday()#include <stdlib.h>  // for random()using namespace std;unsigned int getRandomNum();int main(){cout<<"random1:"<<getRandomNum()<<endl;cout<<"random2:"<<getRandomNum()<<endl;cout<<"random3:"<<getRandomNum()<<endl;cout<<"random4:"<<getRandomNum()<<endl;cout<<"random5:"<<getRandomNum()<<endl;}unsigned int getRandomNum(){// 防止每次生成的随机数一样usleep(1000);struct timeval now_time;gettimeofday(&now_time, NULL);unsigned int msec = now_time.tv_sec + now_time.tv_usec  / 1000;srand(msec);return random();}


0 0
原创粉丝点击