#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++生成不重复的随机整数
最新推荐文章于 2025-03-10 00:48:44 发布
本文介绍了一个使用C++生成指定范围内不重复随机数的程序。通过使用list容器、迭代器、sort和unique函数,确保了生成的随机数既在设定的范围内,又避免了重复。程序首先接收用户输入的数字范围和随机数个数,然后进行有效性检查,最后输出结果。
1万+

被折叠的 条评论
为什么被折叠?



