Algorithm notes-structure-question A: C language 11.1

·Complete a statistical procedure for candidates' votes. Suppose there are 3 candidates named Li, Zhang and Fun. Use structure to store each candidate's name and number of votes. Record the name of the voter for each ballot, and output the final number of votes for each candidate. The structure can be defined in the following format:
struct person { char name[20]; int count; }leader[3] = {"Li", 0, "Zhang", 0, "Fun", 0}; ·First There is an integer n in the row, which means that there are n ballots to be entered. Ensure that n is not greater than 100. In the next n rows, each row contains a person's name, which is the voter of the ballot. Make sure that everyone's name is one of Li, Zhang and Fun. ·There are three rows, which are the number of votes each of Li, Zhang and Fun. The format is to output the name of the person first, followed by a colon, and finally output the number of votes of the candidate. Please pay attention to the line ending output.




  1. Structure
struct person{
	char name[20];
	int count;
}leader[3]={"Li",0,"Zhang",0,"Fun",0};
  1. Main function
for(int i=0;i<n;i++){  
	cin>>name;
	if(strcmp(leader[0].name,name)==0)
	   leader[0].count++;
	if(strcmp(leader[1].name,name)==0)
	   leader[1].count++;
	if(strcmp(leader[2].name,name)==0)
	   leader[2].count++;
}
for(int i=0;i<3;i++)
	cout<<leader[i].name<<":"<<leader[i].count<<endl;

Use the strcmp function to indicate that when the two strings are exactly the same, the return value is 0, and string.h needs to be added to the header file

3. Complete code

#include<iostream>
#include<cstring>
using namespace std;
struct person{
	char name[20];
	int count;
}leader[3]={"Li",0,"Zhang",0,"Fun",0};
int main(){
	char name[20];
	int n;
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>name;
		if(strcmp(leader[0].name,name)==0)
		   leader[0].count++;
		if(strcmp(leader[1].name,name)==0)
		   leader[1].count++;
		if(strcmp(leader[2].name,name)==0)
		   leader[2].count++;
	}
	for(int i=0;i<3;i++)
		cout<<leader[i].name<<":"<<leader[i].count<<endl;
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_44549439/article/details/112590156