为下面的代码标上注释#includestdioh#includestringhstruct houxuan char name20; int votes;;int main struct houxuan people501; char name20; int i=0; fori=0;i501;i++ peopleivotes=0; i
#include<stdio.h> #include<string.h> struct houxuan{ char name[20]; //定义候选人名字的字符数组 int votes; //定义候选人获得的票数 }; int main(){ struct houxuan people[501]; //定义一个由501个候选人结构体组成的数组 char name[20]; //定义输入的候选人名字的字符数组 int i=0; //定义计数器i,用于记录候选人的数量 for(i=0;i<501;i++){ //循环给所有候选人的票数都初始化为0 people[i].votes=0; } i=0; //将计数器i重新赋值为0,用于记录当前输入到第几个候选人 while(gets(name),name[0]!='#'){ //当输入的名字不是“#”时进行循环 int flag=0; //定义一个标志位,用于判断当前输入的名字是否已经存在于候选人数组中 for(int j=0;j<i;j++){ //循环遍历已经存在的候选人名单 if(strcmp(people[j].name,name)==0){ //如果当前输入的名字和已经存在的某个候选人名字相同 people[j].votes++; //该候选人获得的票数加1 flag=1; //将标志位设为1,表示输入的名字已经存在于候选人数组中 break; //退出循环 } } if(flag==0){ //如果标志位为0,表示输入的名字不存在于候选人数组中 int m=0; //定义一个计数器m,用于记录当前输入的名字的字符数量 while(name[m]!='\0'){ //循环将当前输入的名字复制到候选人数组中 people[i].name[m]=name[m]; m++; } people[i].name[m]='\0'; //给候选人名字的最后一个字符赋值为'\0',表示字符串结束 people[i].votes+=1; //该候选人获得的票数加1 i++; //计数器i加1,表示又新增了一个候选人 } } int max=0; //定义一个变量max,用于记录获得最多票数的候选人在数组中的下标 for(int j=1;j<i;j++){ //循环遍历所有的候选人 if(people[j].votes>people[max].votes){ //如果当前候选人获得的票数比已经记录的最多票数的候选人获得的票数还要多 max=j; //将变量max更新为当前候选人在数组中的下标 } } printf("%s",people[max].name); //输出获得最多票数的候选人的名字 return 0; //程序结束
原文地址: https://www.cveoy.top/t/topic/crBb 著作权归作者所有。请勿转载和采集!