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;}運行結果:

這個程序可以用于班級內部按照學號進行隨機抽簽。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
| 
 
 | 
新聞熱點
疑難解答
圖片精選