【C/PTA】Special exercises for structures

This article combines PTA special exercises to guide readers to master the structure. The main topic is supplemented by comments, so that readers can understand the ideas in the code. No other details will be described too much.

6-1 Choose the captain

Xiao Ming likes to play a new game recently. In this game, you need to form a team to complete tasks to obtain rewards. Xiao Ming selected all the team members (each with different abilities) and needed a function to select the team leader (the player with the strongest ability).
Function interface definition:

void showCaptain(TeamMember team[], int n);

Parameter description: n TeamMembers are stored starting from subscript 0 in team, n>0.
Function: Find the captain and output his information
Referee test program example:

#include<stdio.h>

#include<stdlib.h>

#define NAME_LEN 100

#define SEX_LEN 6

typedef struct {
    
    

int id;//身份证号码

    char lastname[NAME_LEN+1];//姓

    char firstname[NAME_LEN+1];//名

    char sex[SEX_LEN];//性别

    double ability;

} TeamMember;


void showCaptain(TeamMember team[], int n);

int main()

{
    
    

    TeamMember *team;

    int n;

    int i;


    scanf("%d",&n);

    team = (TeamMember *)malloc(n*sizeof(TeamMember));

    for(i=0;i<n;i++)

    {
    
    

        scanf("%d %s %s %s %lf",&team[i].id,team[i].lastname, team[i].firstname, team[i].sex, &team[i]. ability);

    }


    showCaptain(team, n);


    return 0;

}


/* 您提交的代码将放置在这里 */

Input example:

3
123456 zhang san male 100
123457 li si female 200.5
123458 wang ming male 159.1

Output sample:

123457 li si female 200.50

void showCaptain(TeamMember team[], int n)
{
    
    
	double x=team[0].ability;int y=0;
	for(int i=0;i<n;i++)
	{
    
    
		if(x<team[i].ability)
		{
    
    
			x=team[i].ability;
			y=i;
		}
	}
	printf("%d %s %s %s %.2f",team[y].id,team[y].lastname,team[y].firstname,team[y].sex,team[y].ability);
}

6-2 Statistics of student performance by level

This question requires the implementation of a simple function that sets students' grades according to their scores and counts the number of students who failed.
Function interface definition:

int set_grade( struct student *p, int n );

where p is a pointer to a structure array of student information. The structure is defined as:

struct student{
    
    
    int num;
    char name[20];
    int score;
    char grade;
};

n is the number of array elements. The student number num, name and score have all been stored. The set_grade function needs to set the student's grade based on their score. Level setting: 85-100 is A, 70-84 is B, 60-69 is C, 0-59 is D. At the same time, set_grade also needs to return the number of people who failed.
Sample Referee Test Procedure:

#include <stdio.h>

#define MAXN 10


struct student{
    
    

    int num;

    char name[20];

    int score;

    char grade;

};


int set_grade( struct student *p, int n );


int main()

{
    
       struct student stu[MAXN], *ptr;

    int n, i, count;

    

    ptr = stu;

    scanf("%d\n", &n);

    for(i = 0; i < n; i++){
    
    

       scanf("%d%s%d", &stu[i].num, stu[i].name, &stu[i].score);

    } 

   count = set_grade(ptr, n);

   printf("The count for failed (<60): %d\n", count);

   printf("The grades:\n"); 

   for(i = 0; i < n; i++)

       printf("%d %s %c\n", stu[i].num, stu[i].name, stu[i].grade);

    return 0;

}


/* 你的代码将被嵌在这里 */

Input example:

10
31001 annie 85
31002 bonny 75
31003 carol 70
31004 dan 84
31005 susan 90
31006 paul 69
31007 pam 60
31008 apple 50
31009 nancy 100
31010 bob 78

Output sample:

The count for failed (<60): 1
The grades:
31001 annie A
31002 bonny B
31003 carol B
31004 dan B
31005 susan A
31006 paul C
31007 pam C
31008 apple D
31009 nancy A
31010 bob B

int set_grade( struct student *p, int n )
{
    
    
	int count=0;
	for(int i=0;i<n;i++)
	{
    
    
		if(p[i].score<=100&&p[i].score>=85)
		p[i].grade='A';
		if(p[i].score<=84&&p[i].score>=70)
		p[i].grade='B';
		if(p[i].score<=69&&p[i].score>=60)
		p[i].grade='C';
		if(p[i].score<=59&&p[i].score>=0)
		{
    
    
	    p[i].grade='D';	
	    count++;
		}
	}
	return count;
}

6-3 Student performance ratio

The student structure is defined as follows:

struct Student{
    
    
    int sid;
    int C;
    int English;
};

Among them, sid is the student number, C is the C language course score, and English is the English course score. Students' scores are compared according to this rule:

先比较两门课的总成绩,总成绩高的为优;
若总成绩相同,再比较C语言成绩,C语言成绩高的为优;
若C语言成绩也相同,则说明两名学生成绩相等。

Write a function to compare scores.
Function interface definition:

int compareScore(const struct Student *s1, const struct Student *s2);

Among them, s1 and s2 are the parameters passed in, pointing to the structure variables of the two students respectively. The function return value is int type,

若s1所指学生成绩优于s2所指学生,返回1;
若s2所指学生成绩优于s1所指学生,返回-1;
若两学生成绩相等,返回0。

Sample Referee Test Procedure:

/* This test program is an example only, the actual test program may be different.

Note: The actual test program may have multiple sets of inputs, multiple comparisons, and the input formats may also be different.

Therefore, do not write code for the test program example, but write a function that meets the requirements of the question */

#include <stdio.h>

struct Student{
    
    

    int sid;

    int C;

    int English;

};

int compareScore(const struct Student *s1, const struct Student *s2);

int main(){
    
    

    struct Student zs, ls;

    scanf("%d%d%d", &zs.sid, &zs.C, &zs.English);

    scanf("%d%d%d", &ls.sid, &ls.C, &ls.English);

    int r;

    r = compareScore(&zs, &ls);

    if(r < 0) printf("Less\n");

    else if(r > 0) printf("Greater\n");

    else printf("Equal\n");

    return 0;

}

/* 你所编写的函数代码将被嵌在这里 */

Input example 1:

For the input format of the sample test program:

1 95 90
2 90 91

Output sample 1:

For the output format of the sample test program:

Greater

Input example 2:

For the input format of the sample test program:

1 90 95
2 95 90

Output sample 2:

For the output format of the sample test program:

Less

int compareScore(const struct Student *s1, const struct Student *s2){
    
    
	if(s1->C+s1->English>s2->C+s2->English)
	return 1;
	else if(s1->C+s1->English<s2->C+s2->English)
	return -1;
	else if(s1->C+s1->English==s2->C+s2->English)
	{
    
    
		if(s1->C>s2->C)
		return 1;
		else if(s1->C<s2->C)
		return -1;
		else if(s1->C==s2->C)
	    return 0;
	}
}

6-4 overall score

Xiao Ming’s company designed an examination program for recruiting new employees. Examination will be conducted from five aspects: expressive ability, logical ability, humanistic quality, scientific quality, and computational thinking. Comprehensive score = Expressive ability 0.4 + Logical ability 0.5 + Humanistic quality 0.3 + Scientific quality 0.6 + Computational thinking * 0.8. It is required to define a function to calculate the comprehensive score.
Function interface definition:

double getAverage(Applicant *a);

A candidate's test score is stored in a. Request the return of comprehensive scores.
Sample Referee Test Procedure:

#include <stdio.h>

#include <stdlib.h>

typedef struct{
    
    

    int presentation;

    int logical;

    int humanistic;

    int scientific;

    int computational;

}Applicant;

double getAverage(Applicant* a);

int main()

{
    
    

    Applicant a;

    double overall;

    scanf("%d%d%d%d%d", &a.presentation,&a.logical,&a.humanistic,&a.scientific,&a.computational);

    overall = getAverage(&a);

    printf("%.2f\n",overall);

    return 0;

}

/* The code you submit will be placed here */

Input example:

100 100 100 100 100

Output sample:

260.00

double getAverage(Applicant *a)
{
    
    
	double sum=0;
	sum=0.4*a->presentation+0.5*a->logical+0.3*a->humanistic+0.6*a->scientific+0.8*a->computational;
	return sum;
}

6-5 Use the "selection sort algorithm" to sort the structure array

This question: Supplement the remaining part of the function sortByChoose(). The requirement is to use the selection sort algorithm to sort the elements of the structure array in descending order according to the student's score (score).
Function interface definition:

void sortByChoose(struct Student *pData,int n)

Sample Referee Test Procedure:

#include<stdio.h>

#include<stdlib.h>

#define N 10

struct Student

{
    
    

    int num;

    int score;

};    


void sortByChoose(struct Student *pData,int n);


int main(void)

{
    
        

    struct Student data[10],*p;

    int i;


    for(p=data,i=0;i<N;i++)

    {
    
    

        scanf("%d %d",&p->num,&p->score);

        p++;

    }

    sortByChoose(data,N);

    for (p=data,i=0;i<N;i++)

    {
    
    

        printf("%2d-%-5d", p->num, p->score);

        p++;

    }


    return 0;

}


void sortByChoose(struct Student *pData,int n)

{
    
    

    struct Student *p1,*p2,*p;

    int num, score,i,j;

    for(p1=pData;p1<pData+n-1;p1++) 

    {
    
    

    /* 请在这里填写答案 */

       }

}

Input example:

29 90
15 80
87 55
65 84
35 80
33 55
44 79
99 80
89 80
41 55

Output sample:

29-90 65-84 15-80 35-80 99-80 89-80 44-79 87-55 33-55 41-55

p=p1;
for(p2=p1+1;p2<pData+n;p2++)
{
    
    
    if(p2->score>p->score)//判断
    {
    
    
        p=p2;
    }
}

if(p!=p1)//交换
{
    
    
    num=p->num;
    p->num=p1->num;
    p1->num=num;

    score=p->score;
    p->score=p1->score;
    p1->score=score;
}

6-6 Maximum value of structure

The definition of student type ST is as follows:

typedef struct student{
    
    
char name[10],id[10];
int gender;
int age;
double scored;
} ST;

Write a function to return the address of the highest score of a boy or girl in the specified student array (convention: integers 0 and 1 represent boys and girls respectively).
Function interface definition:

ST* MaxST(ST d[],int n,int k);//k=0|1

where d is the initial address of the student array, n is the length of the array, k is the gender description to be found (the value must be 0 or 1), the function must return the address of the highest scorer among the specified type of students, if If it does not exist, an empty address is returned.
Sample Referee Test Procedure:

Here is an example of a function being called for testing. For example:

#include <stdio.h>

#include <stdlib.h>

typedef struct student{
    
    

    char name[10],id[10];

    int gender;

    int age;

    double scored;

} ST;

void output(ST *d){
    
    //输出一个记录

    if(d==NULL) {
    
    printf("null\n");return;}

    printf("%s,%s,%d,%d,%4.2f\n",d->name,d->id,d->gender,d->age,d->scored);

}

ST* InitData(int n);//从输入设备上输入相关数据,略去不表


ST* MaxST(ST d[],int n,int k);//k=0|1  <--需要完成的函数:找最值


int main(){
    
    

    int i,n;scanf("%d\n",&n);

    ST *p=InitData(n);

    output(MaxST(p,n,0));    

    output(MaxST(p,n,1));

    free(p);

    return 0;

}

/* 请在这里填写答案 */

Input example:

The first line is the number of records, and the remaining lines are related data (separated by spaces, one per line).

6
Marry.MK 20201125 0 19 92.86
J.Mark 20201185 0 17 90.93
rouh.M 20201102 1 18 79.51
byi.beee 20201129 1 17 90.28
floyd.Fd 20201150 0 17 81.16
grdda 20201146 1 19 85.52

Output sample:

Output the highest score among male and female students (you only need to find and return its address, input, and output are completed by the test program).

Marry.MK,20201125,0,19,92.86
byi.beee,20201129,1,17,90.28

ST* MaxST(ST d[],int n,int k)
{
    
    
    double max=-1;//初始化最高分为一个较小的值
    int index=-1;//初始化索引为-1,表示不存在满足条件的学生

    for(int i=0;i<n;i++)
    {
    
    
        if(d[i].gender==k)//根据输入的性别条件进行筛选
        {
    
    
            if(d[i].scored>max)//找到性别符合条件的学生中的最高分
            {
    
    
                max=d[i].scored;
                index=i;//更新最高分的索引
            }
        }
    }

    if(index!=-1)
    {
    
    
        return &d[index];//返回最高分学生的地址
    }
    else
    {
    
    
        return NULL;//如果不存在满足条件的学生,返回空地址
    }
}

6-7 Complex number multiplication operation

This question requires the implementation of a function that can calculate the product of two complex numbers.
Function interface definition:

PLEX multi(PLEX a,PLEX b);

where a and b are both complex numbers, the return value is also a complex number, and the value is the value of a*b.
Sample Referee Test Procedure:

#include <stdio.h>

typedef struct

{
    
    

    float re,im;

}PLEX;


PLEX multi(PLEX a,PLEX b);


int main()

{
    
    

    PLEX x,y,z;

    scanf("%f%f",&x.re,&x.im);

    scanf("%f%f",&y.re,&y.im);

    z=multi(x,y);

    if(z.im>=0)

        printf("%.2f+%.2fi",z.re,z.im);

    else

        printf("%.2f%.2fi",z.re,z.im);

    return 0;

}


/* 请在这里填写答案 */

Input example:

1 2
3 4

Output sample:

-5.00+10.00 a.m

PLEX multi(PLEX a,PLEX b)
{
    
    
	PLEX T;
	T.re=a.re*b.re-a.im*b.im;
	T.im=a.re*b.im+a.im*b.re;
	return T;
}

7-5 a gang of one

"Gang-one study group" is a common learning organization method in primary and secondary schools. Teachers arrange students with high academic performance into a group with students with low academic performance. This question asks you to write a program to help the teacher automatically complete this assignment. That is, after getting the ranking of the whole class, among the students who are not yet grouped, divide the top-ranked students into one group with the bottom-ranked students of the opposite sex. Group.
Input format:

The first line of input gives a positive even number N (≤50), which is the number of students in the class. In the following N lines, each student's gender (0 represents a girl, 1 represents a boy) and name (a non-empty string of no more than 8 English letters) are given in order from high to low, separated by a space. . It is guaranteed here that the male to female ratio in this class is 1:1, and there will be no tied rankings.
Output format:

Output a set of two student names per line, separated by 1 space. Students with higher rankings are in front and students with lower rankings are in the back. The output order of the group is arranged from high to low according to the ranking of the previous students.
Input example:

8
0 Amy
1 Tom
1 Bill
0 Cindy
0 Maya
1 John
1 Jack
0 Linda

Output sample:

Amy Jack
Tom Linda
Bill Maya
Cindy John

#include <stdio.h>
int main()
{
    
    
	int n;scanf("%d",&n);
	int sex[n];char name[n][9];
	
	for(int i=0;i<n;i++)
	{
    
    
		scanf("%d %s",&sex[i],name[i]);
	}
	
	int exist[n]={
    
    0};
	for(int p=0;p<n/2;p++)//与后面的printf相呼应,保证输出的时候名次高的在前
	{
    
    
		for(int q=n-1;q>=n/2;q--)
		{
    
    
			if(sex[p]!=sex[q]&&exist[p]==0&&exist[q]==0)//如果性别不同且没组过队
			{
    
    
				printf("%s %s\n",name[p],name[q]);
				exist[p]=exist[q]=1;
			}
		}
	}
}

7-6 Examination seat number

Each PAT candidate will be assigned two seat numbers when taking the exam, one for the test machine and one for the exam. Under normal circumstances, candidates first get the test seat number when entering. After entering the test state, the system will display the candidate's test seat number. Candidates need to change to the test seat during the test. But some candidates are late and the test machine test has ended. They can only ask you for help with the test machine seat number they received and find out their test seat number from the backend.
Input format:

The first line of input gives a positive integer N (≤1000), followed by N lines, each line gives a candidate's information: admission ticket number, test machine seat number, exam seat number. The admission ticket number consists of 16 digits, and the seats are numbered from 1 to N. The input ensures that each person's admission ticket number is different and no two people will be assigned to the same seat at any time.

After the candidate information, a positive integer M (≤N) is given, followed by M test machine seat numbers to be queried in one line, separated by spaces.
Output format:

corresponds to each test seat number that needs to be queried, and outputs the corresponding candidate's admission ticket number and exam seat number in one line, separated by a space.
Input example:

4
3310120150912233 2 4
3310120150912119 4 1
3310120150912126 1 3
3310120150912002 3 2
2
3 4

Output sample:

3310120150912002 2
3310120150912119 1

#include <stdio.h>
int main()
{
    
    
	int n;scanf("%d",&n);
	char sfz[n][20];int sj[n],ks[n];
	for(int i=0;i<n;i++)
	{
    
    
		scanf("%s",sfz[i]);
		scanf("%d %d",&sj[i],&ks[i]);
	}
	int m;scanf("%d",&m);
	int chaxun[m];
	for(int i=0;i<m;i++)
	{
    
    
		scanf("%d",&chaxun[i]);
		int s=chaxun[i];
		for(int j=0;j<n;j++)
		{
    
    
			if(s==sj[j])
			{
    
    
				printf("%s %d\n",sfz[j],ks[j]);
			}
		}
	}
}

Supongo que te gusta

Origin blog.csdn.net/2301_77485708/article/details/134814553
Recomendado
Clasificación