C++抽獎程式實現方法_C 語言

來源:互聯網
上載者:User

本文執行個體講述了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()範圍要求擴大的時候,浮點與整形數之間的強制轉換問題。

複製代碼 代碼如下:
int  randId = (int)((double)rand() / RAND_MAX * num);

②STL中set的使用是否非常熟練?

希望本文所述對大家的C++程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.