本文實例講述了C++抽獎程序實現方法。分享給大家供大家參考。具體實現方法如下:
一、int rand()可以生成從[0, 65536)之間均勻分布的隨機數。
現要求實現:有30萬員工,使用rand()寫一個抽獎程序,抽出人100獲獎。
- #include <iostream>
- #include <set>
- using namespace std;
- typedef set<int> ISET;
- ISET GetPridePersonId(const int num, const int pride_num)
- {
- int id;
- ISET iset;
- while (1) {
- id = (int)((double)rand() / RAND_MAX * num) % (num - 1);
- if (iset.find(id) == iset.end()) {
- iset.insert(id);
- }
- if (iset.size() >= pride_num) {
- break;
- }
- }
- return iset;
- }
- void print(ISET &iset)
- {
- ISET::iterator iter;
- cout<<"item as :/n";
- for (iter = iset.begin(); iter != iset.end(); ++ iter) {
- cout<<*iter<<"/n";
- }
- }
- int main(int argc, char **argv)
- {
- const int total_person = 300000;
- const int total_pride_person = 100;
- ISET iset = GetPridePersonId(total_person, total_pride_person);
- print(iset);
- return 0;
- }
二、主要容易出錯的地方:
①當rand()范圍要求擴大的時候,浮點與整形數之間的強制轉換問題。
②STL中set的使用是否非常熟練?
希望本文所述對大家的C++程序設計有所幫助。
新聞熱點
疑難解答