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

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

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

 1 #include<stdio.h>
 2 #include<string.h>
 3 #define NUM 10  //投票的人数
 4 #define K 4  //候选人数
 5 struct vote{
 6     char name[10];
 7     int num;
 8 }candidate[K]={"Mark", 0, "wrr", 0, "Mary", 0, "Kay", 0};
 9 
10 void main(){
11     char input[10];
12     int i, j, m=0, n=0, max=0;
13 
14     printf("		Welcome to the voting system!
");
15     printf("		candidate:");
16     for(j=0;j<K;j++){
17         printf("%s ", candidate[j].name);
18     }
19     printf("
");
20 
21     for(i=0;i<NUM;i++){
22         printf("No.%d is voting ,name is :", i+1);
23         scanf("%s",input);
24         for(j=0;j<K;j++){
25             if(strcmp(candidate[j].name, input)==0){
26                 n=candidate[j].num++;
27             }
28             if(max<n){
29                 max=n;
30                 m=j;
31             }
32         }
33     }
34     printf("

");
35 //int strcmp(char *a, char *b)  比较字符串a, b    
36 //a<b, 返回负数; a=b,返回 0 ; a>b,返回正数
37     for(j=0;j<K;j++){
38         printf("%s's number of votes is %d
", candidate[j].name, candidate[j].num);
39     }
40 
41     printf("
The victor is %s !!! 
The number of votes is %d

", candidate[m].name, max+1);
42 }

结果为:

原文地址:https://www.cnblogs.com/kailugaji/p/8595609.html