1、使用rand()函数
简介:
1、rand()不需要参数,它会返回一个从0到最大随机数的任意整数,最大随机数的大小通常是固定的一个大整数。
2、表获取 a~b 之间的一个随机整数:rand() % (b-a+1)+ a
3、rand() 会返回一随机数值,范围在 0 至 RAND_MAX 间。为了避免出现重复的数字,在调用此函数产生随机数前,必须先利用 srand()设置好随机数种子,如果未设随机数种子,rand()在调用时会自动设随机数种子为 1。
代码:
#include <iostream>
#include <fstream>
#include <vector>
#include <cstdlib>
#include <time.h>
using namespace std;
int main()
{
int len = 1000000;
ofstream file("data.txt", ios::trunc);
if (!file.is_open())
{
cout << "open file fair" << endl;
return 0;
}
srand((unsigned)time(NULL));
for (int i = 0; i < len/10; i++)
{
for (int j = 0; j < 9; j++)
{
file <<rand()%len<<" ";
}
file <<rand()%len<<endl;
}
file.close();
}
生成数据:
2、使用random_shuffle()函数
简介:
1、使用rand()函数,发现仍然生成重复的数字
2、random_shuffle()函数:打乱原数组中的数据
代码:
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <time.h>
using namespace std;
int main()
{
int len = 1000000;
ofstream file("data.txt", ios::trunc);
if (!file.is_open())
{
cout << "open file fair" << endl;
return 0;
}
vector<int>num(len);
for(int i=0;i<len;i++)
{
num[i]=i;
}
random_shuffle(num.begin(),num.end());
for (int i = 1; i <= len; i++)
{
if(i%10==0)file<<endl;
file <<num[i-1]<<" ";
}
file.close();
}