C language | Count the results of voting

Example 38: There are three candidates, and each voter can only vote for one person. It is required to compile a program for counting votes in C language, input the names of candidates one after another, and finally output the results of each person's votes.

Problem-solving idea: You need to design a structured array, which contains 3 elements, and the information in each element should include the candidate's name and the number of votes.

Source code demo:

#include<stdio.h>//头文件 
#include<string.h>//引入strcmp 
 struct people//定义结构体变量 
 {
    
    
   char name[20];//定义字符数组 
   int number;//定义整型变量 
 } leader[3]={
    
    "li",0,"zhang",0,"sun",0}; /*数组的定义和引用不一样,把姓赋给数组name 把0赋给 shu*/
 int main()//主函数 
 {
    
    
   int i,j;//定义整型变量 
   char leader_name[20];//定义字符数组 
   for(i=1;i<10;i++)//for循环,循环9次 
   {
    
    
     printf("请输入人名\n");//提示语句 
     scanf("%s",leader_name);//键盘输入名字 
     for(j=0;j<3;j++)
    if(strcmp(leader_name,leader[j].name)==0)//比较两个字符串,如果名字相等 
     {
    
    
       leader[j].number++;//票数加1 
     }
   } 
   printf("结果是:\n");//提示语句 
   for(i=0;i<3;i++)//for循环 
   {
    
    
      printf("%s票数:%d\n",leader[i].name,leader[i].number);//输出名字和票数 
  } 
   return 0;//主函数返回值为0 
 }

The compilation and running results are as follows:

请输入人名
li
请输入人名
zhang
请输入人名
sun
请输入人名
sun
请输入人名
li
请输入人名
li
请输入人名
li
请输入人名
sun
请输入人名
sun
结果是:
li票数:4
zhang票数:1
sun票数:4

--------------------------------
Process exited after 23.01 seconds with return value 0
请按任意键继续. . .

C language statistical voting results
More cases can go public account: C language entry to proficient

Guess you like

Origin blog.csdn.net/weixin_48669767/article/details/111352359