栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

IDE是vs013。

#include "stdafx.h"
#include  
#include 
#include  
#include 
#include
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
 srand((unsigned)time(NULL));
 list::iterator it;//迭代器
 list 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;
}

运行结果:

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/62328.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号