C++生成不重復的隨機整數(shù)
更新時間:2019年09月18日 14:14:22 作者:pythontojava
這篇文章主要為大家詳細介紹了C++生成不重復的隨機整數(shù),具有一定的參考價值,感興趣的小伙伴們可以參考一下
C++生成不重復的隨機數(shù),供大家參考,具體內(nèi)容如下
給定正整數(shù)的范圍[n,m],生成k個不重復的隨機數(shù)字。
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;//定義鏈表,保存生成的隨機數(shù)
int begin, end;//數(shù)字范圍
int sum;//隨機數(shù)個數(shù)
cout << "輸入數(shù)字范圍([n,m]):";
cin >>begin>>end;
cout << "輸入隨機數(shù)個數(shù):";
cin >> sum;
if ( (end<0)||(begin<0)||(begin >end)|| (sum>end))//起始范圍必須大于0,且隨機數(shù)個數(shù)小于等于最大數(shù)字范圍
{
cout << "范圍錯誤";
cout << endl;
system("pause");
return 0;
}
else
{
while (l.size() < sum)
{
l.push_back(rand() % (end - begin + 1) + begin);
l.sort();//排序
l.unique();//去除相鄰的重復隨機數(shù)中的第一個
}
cout << "結果:";
}
for (it = l.begin(); it != l.end(); it++)
{
cout << *it << ' ';
}
cout << endl;
system("pause");
return 0;
}
運行結果:

這個程序可以用于班級內(nèi)部按照學號進行隨機抽簽。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

