/*
模拟n个人参加选举的过程,并输出选举结果:假设候选人有四人,分别用A、B、C、D表示,当选某候选人时直接输入其编号(编号由计算机随机产生),若输入的不是A、B、C、D则视为无效票,选举结束后按得票数从高到低输出候选人编号和所得票数。
*/
#include <stdio.h>
#include <stdlib.h>
#define M 100000000
struct ticketCount {
char name;
int count;
} candidate[5] = {{'A',0},{'B',1},{'C','2'},{'D','3'},{'E','4'}};
int main(int argc, const char * argv[]) {
// insert code here...
// 随机投票
for (int i= 0; i< M; i++) {
int tmp = arc4random_uniform(10);
switch (tmp) {
case 0:
candidate[0].count++;
break;
case 1:
candidate[1].count++;
break;
case 2:
candidate[2].count++;
break;
case 3:
candidate[3].count++;
break;
default:
candidate[4].count++;
break;
}
}
// 冒泡排序
for (int i= 0; i< 4-1; i++) {
for (int j= 0; j< 4-1-i; j++) {
if (candidate[j].count<candidate[j+1].count) {
int tmp = candidate[j].count;
candidate[j].count = candidate[j+1].count;
candidate[j+1].count = tmp;
char tmpaCh = candidate[j].name;
candidate[j].name = candidate[j+1].name;
candidate[j+1].name = tmpaCh;
}
}
}
//printf("选举结果票数从高到低排序:\n");
for (int i= 0; i< 4; i++) {
printf("候选人:%c,票数:%d;\n",candidate[i].name,candidate[i].count);
};
//printf("无效票数:%d;\n",candidate[4].count);
printf("The end!\n");
return 0;
}
|
|