Structure storage data

Structure storage data

mission details

This task: There are three candidates, each voter can only cast one vote, write a program, use the structure to store the data, and find the result of the vote.

The three candidates are "Li", "Zhang", and "Sun".

Programming requirements

Supplement the code, use the structure to store the data, and find the result of the vote.

test introduction

The platform will test the code you write and compare the value you output with the actual correct value. Only when all the data are calculated correctly can the test pass:

Test input:

10
Li
Li
Sun
Zhang
Zhang
Sun
Li
Sun
Zhang
Li

Expected output:

Li:4
Zhang:2
Sun:3

Test input data description:

The first line of input data contains an integer n, which means that there are n people voting. Each subsequent line contains the name of a certain candidate.

code show as below

#include<stdio.h>
#include<string.h>
typedef struct candidate     /*定义结构体类型*/
{
    
    
	char name[20];       /*存储名字*/
	int count;              /*存储得票数*/
}CAND;                    /*定义结构体数组*/

int main()
{
    
    
	CAND cndt[3] = {
    
     {
    
    "Li",0},{
    
    "Zhang",0},{
    
    "Sun",0} };
	int i, j,n;
	scanf("%d", &n);
	char leader_name[20];
	for (i = 1; i <= n; i++)
	{
    
    
		scanf("%s", leader_name);
		for (j = 0; j <= 2; j++)
		{
    
    
			if (strcmp(leader_name, cndt[j].name) == 0)
			{
    
    
				cndt[j].count++;
			}
		}
	}
	for (i = 0; i <= 2; i++)
	{
    
    
		printf("%s:%d\n", cndt[i].name, cndt[i].count);
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_51705589/article/details/112969351