4、抽奖小程序:共有N人参加抽奖(名单从namelist.txt中读取),先随机抽取N3个三等奖,然后随机抽取N2个
二等奖,最后随机抽取N1个一等奖,其中N3>N2>N1,且N3+N2+N1<N。编写程序,从名单中读入所有参加抽奖人名,
然后依次抽奖,并输出获奖名单。
(不能重复参加抽奖,程序取名hw15_04.cpp)
#include <iostream>
#include <fstream>
#include <cstring>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
const int N = 42; // 总人数
const int N3 = 10; // 三等奖人数
const int N2 = 5; // 二等奖人数
const int N1 = 1; // 一等奖人数
int main()
{
srand(time(0));
string name[N];
const int ns = N1 + N2 + N3;
int numberlist[ns]{0};
ifstream fstrm("namelist.txt", ios::in);
for(int i=0; i<N; i++)
{
fstrm >> name[i]; // 以空格为数据分隔符
}
int count = 0;
cout <<"start" << endl << "3rd*" << N3 << endl;
while (count < ns) {
int r = (rand() % (N-1));
for (int j=0; j <= count; j++) {
if (numberlist[j] == r) {
continue;
}
}
numberlist[count] = r;
cout << name[r] << " ";
count += 1;
if (count == N3) {
cout <<endl<< "2nd*" << N2 << endl;
}
if (count == ns-N1)
cout <<endl<< "1st*" << N1 << endl;
}
return 0;
}
Post Views: 9