产生范围
(a, b)之间
均匀分布的double数:
#include <iostream> #include <time.h> #include <stdlib.h> using namespace std; int main() { srand( (int)time(0) ); //generate the seed for random number; //time(0) or time(NULL) return the current system time in seconds, //so if you run the code twice within one second, it will generate the same //random number lists!!! double rnd; double a=0, b=10; rnd = (double) rand()/RAND_MAX * (b-a) + a; cout<<rnd<<endl; srand((int)time(0)); rnd = (double) rand()/RAND_MAX * (b-a) + a; cout<<rnd<<endl; // The same number as above return 0; } 其他可能的种子发生器。 上面time(0)只能表示秒级(返回从1970.1.1到当前经过了多少秒),在linux下可调用如下方法产生微秒级(1 microsecond=10^(-6) second)系统时间。 #include <sys/time.h> struct timeval tv; gettimeofday(&tv, NULL); cout<<tv.tv_sec<<" "<<tv.tv_usec<<endl; tv_sec 为秒; tv_usec为微秒; —————————— Data Type: struct timeval The
long int tv_sec
long int tv_usec
为什么编程语言以及数据库要从1970年1月1 日开始计算时间 请参见此文: blog.chinaunix.net/u3/103146/showart_2050726.html |
产生均匀分布随机数的C++程序
最新推荐文章于 2023-10-17 23:17:54 发布