温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-08-31 12:54:17 来源:脚本之家 阅读:248 作者:pythontojava 栏目:编程语言

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

运行结果:

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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI