选民该如何写???
1.先对选民初始化;即定义候选人。
2.投票;即比对候选人名单进行统计。
3.打印出结果;既把统计的结果打印出来,可以利用从大到小的顺序进行排列。
需要的知识体系
结构体、数组
本次代码只定义三个候选人,总共10张票,没有定义废票的情况,接下来就敲敲代码把
#include <stdio.h>
#include <stdlib.h>
struct vote {
char *name;
int poll;
};
void initXuanMin(struct vote *XuanMin, int len) {
int i;
for (i = 0; i < len; i++) {
printf("input %d name:\n", i + 1);
XuanMin[i].name = (char *)malloc(20);
scanf("%s", XuanMin[i].name);
XuanMin[i].poll = 0;
}
}
void getMatXuanMin(struct vote *XuanMin, int len) {
int i;
int j;
char name[128];
for (i = 0; i < 10; i++) {
printf("input %d vote's name:\n", i + 1);
scanf("%s", name);
for (j = 0; j < len; j++) {
if (strcmp(name, XuanMin[j].name) == 0) {
XuanMin[j].poll++;
}
}
}
}
int printXuanMinForPaiXu(struct vote *XuanMin, int len) {
int i;
int tmp;
printf("ret:\n");
for (i = 0; i < len; i++) {
if (XuanMin[i].poll < XuanMin[i + 1].poll) {
tmp = XuanMin[i].poll;
XuanMin[i].poll = XuanMin[i + 1].poll;
XuanMin[i + 1].poll = tmp;
}
printf("name:%s,poll:%d\n", XuanMin[i].name, XuanMin[i].poll);
}
}
int main() {
struct vote XuanMin[3];
int len;
len = sizeof(XuanMin) / sizeof(struct vote);
initXuanMin(XuanMin, 3);
getMatXuanMin(XuanMin, 3);
printXuanMinForPaiXu(XuanMin, 3);
return 0;
}
快去试试运行结果把!!!