13、(***)模拟n个人参加选举的过程,并输出选举结果:假设候选人有四人,分别用A、B、C、D表示,当选某候选人时,直接输入其编号(编号由计算机随机产生),
若输入的不是A、B、C、D则视为无效票,选举结束后按得票数从高到低输出候选人编号和所得票数。
要求:取随机数,通过随机数结果判断选票结果并存储到数组中,然后通过下表同时将整形数组与对应的字符数组排序,输出结果。
int main()
{
int people_num;
printf("输入群众人数:");
scanf("%d",&people_num); //群众人数输入
int candidate = 0; //候选人序号
int tickets[4]={0,0,0,0}; //候选人票数a[0],代表A的票数;票数b[0],代表B的票数;票数c[0],代表C的票数;票数d[0],代表D的票数
char people[4]={'A','B','C','D'};
printf("产生的随机票为:");
for (int i = 0; i < people_num; i++)
{
candidate=arc4random()%(4-0+1); //产生随机票,0代表A,1代表B,2代表C,3代表D,4
printf("%d ",candidate);
if (candidate > 3){
continue;
}else{
tickets[candidate]++;
}
}
for ( int i = 0; i <4-1; i++) { //按照选票通过冒泡法排票
for (int j = 0; j< 4 - i -1; j++) {
if (tickets[j] < tickets[j+1]) {
int temp = 0; //选票排序
temp = tickets[j];
tickets[j] = tickets[j+1];
tickets[j+1] = temp;
char temp2 = '0'; //姓名同时排序
temp2 = people[j];
people[j] = people[j+1];
people[j+1] = temp2;
}
}
}
printf(" ");
for (int i = 0; i< 4; i++) {
printf("%c得票%d ",people[i], tickets[i]);
}
return 0;
}