# 如何产生随机数

## 利用C库函数

``````x = rand()%11; /*产生1~10之间的随机整数*/

y = rand()%51 - 25; /*产生-25 ~ 25之间的随机整数*/

z = ((double)rand()/RAND_MAX)*(b-a) + a;/*产生区间[a,b]上的随机数*/
``````

``````#define random(x) (rand()%x)
int main()
{
for (int i = 0; i < 10; ++i)
cout << random(11) << " ";
cout << endl;
system("pause");
}
``````

``````#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;

#define random(a,b) (((double)rand()/RAND_MAX)*(b-a)+a)

void main() {
srand((int)time(0));

for (int i = 0; i < 100; i++) {
cout << random(0, 10) << " ";
}
cout << endl;

system("pause");
}
``````

## C++随机数发生器

``````#include<iostream>
#include<random>
#include<ctime>
using namespace std;

void main() {
default_random_engine e;   //生成随机无符号数
for (size_t i = 0; i < 10; ++i)
cout << e() << " ";

cout << endl;
cout << "seed Random:" << endl;

e.seed(int(time(0)));
for (size_t i = 0; i < 10; ++i)
cout << e() << " ";
system("pause");
}

//OUTPUT:
3499211612 581869302 3890346734 3586334585 545404204 4161255391 3922919429 949333985 2715962298 1323567403
seed Random:
1209134335 963543660 450936573 838635935 555864927 2629301182 2752494759 772597830 1658101593 1483430385

``````

``````#include<iostream>
#include<random>
#include<string>
using namespace std;

vector<unsigned> randVec()
{
static default_random_engine e;
static uniform_int_distribution<unsigned> u(0, 9);
vector<unsigned> ret;
for (size_t i = 0; i < 20; ++i)
ret.push_back(u(e));
return ret;
}

vector<float> normalVec()
{
cout << "正态分布:" << endl;
static default_random_engine e;
static normal_distribution<float> n(4, 1.5);//均值4，方差1.5
vector<float> res;
vector<unsigned> vals(9);
for (size_t i = 0; i != 20; ++i)
{
unsigned tmp = n(e);
unsigned v = lround(tmp);
if (v < vals.size())
++vals[v];
res.push_back(tmp);

}
for (size_t j = 0; j != vals.size(); ++j)
cout << j << ": " << string(vals[j], '*') << endl;
return res;
}

template<typename T>
void display(vector<T> a)
{
for (int i = 0; i < a.size(); ++i)
{
cout << a[i] << " ";
}
cout << endl;
}

void main() {
vector<unsigned> res;
res=randVec();
cout << "均匀分布:" << endl;
display(res);
vector<float> res2;
res2 = normalVec();
display(res2);
system("pause");
}
``````

2018-08-24_13-13-21.png

01.png
02.png