C++ lucky draw program implementation method

  • 2020-04-02 03:08:19
  • OfStack

The example of this paper describes the C++ lottery program implementation method. Share with you for your reference. The specific implementation method is as follows:

Int rand() can generate random Numbers evenly distributed between [0, 65536].

The goal: 300,000 employees, write a lottery program using rand() and draw 100 winners.


#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; 
} 

Ii. Main error-prone areas:

(1) the problem of casting between floating-point and integer Numbers when the range of rand() requires expansion.

int  randId = (int)((double)rand() / RAND_MAX * num);

Is the use of set in STL very skilled?

Hope that the article described in the C++ programming to help you.


Related articles: