C++生成不重复的随机整数

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C++生成不重复的随机整数

  2021-04-02 我要评论

C++生成不重复的随机数,供大家参考,具体内容如下

给定正整数的范围[n,m],生成k个不重复的随机数字。

IDE是vs013。

#include "stdafx.h"
#include <iostream> 
#include <vector>
#include <stdlib.h> 
#include <time.h>
#include<list>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
 srand((unsigned)time(NULL));
 list<int>::iterator it;//迭代器
 list<int> l;//定义链表,保存生成的随机数
 int begin, end;//数字范围
 int sum;//随机数个数
 cout << "输入数字范围([n,m]):";
 cin >>begin>>end;
 cout << "输入随机数个数:";
 cin >> sum;
 if ( (end<0)||(begin<0)||(begin >end)|| (sum>end))//起始范围必须大于0,且随机数个数小于等于最大数字范围
 {
 cout << "范围错误";
 cout << endl;
 system("pause");
 return 0;
 }
 else
 {
 while (l.size() < sum)
 {
 l.push_back(rand() % (end - begin + 1) + begin);
 l.sort();//排序
 l.unique();//去除相邻的重复随机数中的第一个
 }
 cout << "结果:";
 }
 for (it = l.begin(); it != l.end(); it++)
 {
 cout << *it << ' ';
 }
 
 cout << endl;
 system("pause");
 return 0;
}

运行结果:

这个程序可以用于班级内部按照学号进行随机抽签。

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们