C++ 生成不包含重复值的1百万的随机数

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();
}

生成数据:

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值