产生均匀分布随机数的C++程序

本文介绍了如何使用C++编程语言在指定范围内生成均匀分布的double数值,包括种子初始化、时间获取及代码实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

产生范围 (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 struct timeval structure represents an elapsed time. It is declared in sys/time.h and has the following members:

long int tv_sec
This represents the number of whole seconds of elapsed time since 1970.1.1.
long int tv_usec
This is the rest of the elapsed time (a fraction of a second), represented as the number of microseconds. It is always less than one million.
————————

为什么编程语言以及数据库要从1970年1月1 日开始计算时间

请参见此文: blog.chinaunix.net/u3/103146/showart_2050726.html
转载 http://hi.baidu.com/liujtm/blog/item/6613bc63f5b6f46c0c33fade.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值