获取0到1的随机数

这个网址介绍了很多

http://stackoverflow.com/questions/17598547/why-is-the-first-result-of-rand-doublerand-max-is-not-random

and

http://stackoverflow.com/questions/1340729/how-do-you-generate-a-random-double-uniformly-distributed-between-0-and-1-from-c

 

范围是0-1

double X=((double)rand()/(double)RAND_MAX);

 

 1 #include <iostream>
 2 #include <iomanip>
 3 #include <map>
 4 #include <random>
 5 
 6 int main()
 7 {
 8     std::random_device rd;
 9 
10 
11     std::mt19937 e2(rd());
12 
13     std::uniform_real_distribution<> dist(0, 1);
14 
15     std::map<int, int> hist;
16     for (int n = 0; n < 10000; ++n) {
17         ++hist[std::round(dist(e2))];
18     }
19 
20     for (auto p : hist) {
21         std::cout << std::fixed << std::setprecision(1) << std::setw(2)
22                   << p.first << ' ' << std::string(p.second/200, '*') << '\n';
23     }
24 }

 

 范围是0-1

1 #include <stdlib.h>
2 
3 double randZeroToOne()
4 {
5     return rand() / (RAND_MAX + 1.);
6 }

 

 范围是M到N

double randMToN(double M, double N)
{
    return M + (rand() / ( RAND_MAX / (N-M) ) ) ;  
}

 

转载于:https://www.cnblogs.com/liangliangdetianxia/p/4172223.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值