C语言 投票系统:给定候选人,从键盘输入候选人的名字,统计票数,并输出最终获胜者

时间:2023-03-10 00:20:21
C语言 投票系统:给定候选人,从键盘输入候选人的名字,统计票数,并输出最终获胜者

投票系统:给定候选人名单,从键盘输入候选人的名字,统计票数,并输出最终获胜者。若投票人输入的名字不在其候选名单上,则该票数无效。

//凯鲁嘎吉 - 博客园 http://www.cnblogs.com/kailugaji/

 #include<stdio.h>
#include<string.h>
#define NUM 10 //投票的人数
#define K 4 //候选人数
struct vote{
char name[];
int num;
}candidate[K]={"Mark", , "wrr", , "Mary", , "Kay", }; void main(){
char input[];
int i, j, m=, n=, max=; printf("\t\tWelcome to the voting system!\n");
printf("\t\tcandidate:");
for(j=;j<K;j++){
printf("%s ", candidate[j].name);
}
printf("\n"); for(i=;i<NUM;i++){
printf("No.%d is voting ,name is :", i+);
scanf("%s",input);
for(j=;j<K;j++){
if(strcmp(candidate[j].name, input)==){
n=candidate[j].num++;
}
if(max<n){
max=n;
m=j;
}
}
}
printf("\n\n");
//int strcmp(char *a, char *b) 比较字符串a, b
//a<b, 返回负数; a=b,返回 0 ; a>b,返回正数
for(j=;j<K;j++){
printf("%s's number of votes is %d\n", candidate[j].name, candidate[j].num);
} printf("\nThe victor is %s !!! \nThe number of votes is %d\n\n", candidate[m].name, max+);
}

结果为:

C语言 投票系统:给定候选人,从键盘输入候选人的名字,统计票数,并输出最终获胜者