[C Language] Use the structure to output the average score and the student data below or equal to the average score

[C Language] Use the structure to output the average score and the student data below or equal to the average score

1. Topic

The student's record consists of name and grade. Input the data of 4 students in the main function, please write a function to calculate and return the output of the average score, and save the data of the students whose score is lower than or equal to the average score for output through the structure pointer.

Require:

  1. Use the structure:
typedef struct Student 
{
    
    
	char name[20]; 
	int score; 
}Stu;
  1. Use subfunction: float StructAvg(Stu *a,Stu *b,int n,int *m)
  2. to output in the main function.

Input format: Enter the names and scores of 4 students in sequence

Output format: Save and output the data of students whose scores are lower than or equal to the average

Example:

Input:
KOBE 90
YAO 90
HC 80
JAMES 70
Output:
Avg=82.5
HC 80
JAMES 70

2. Complete code

#include <stdio.h>
#define N 4
typedef struct Student {
    
    
    char name[20];
    int score;
}Stu;
float StructAvg(Stu* a, Stu* b, int n, int* m)
{
    
    
    int i, j = 0, sum = 0;
    float avg;
    for (i = 0; i < n; i++)
        sum += a[i].score;
    avg = sum * 1.0 / n;
    for (i = 0; i < n; i++)
        if (a[i].score < avg)
            b[j++] = a[i];
    *m = j;
    return avg;
}
int main()
{
    
    
    int i, j, n;
    float ave;
    struct Student s[N];
    for (i = 0; i < N; i++) {
    
    
        scanf("%s %d", s[i].name, &s[i].score);
    }
    struct Student h[N];
    ave = StructAvg(s, h, N, &n);
    printf("Avg=%.1f\n", ave);
    for (i = 0; i < n; i++)
        printf("%s %d\n", h[i].name, h[i].score);
    printf("\n");
}

3. Screenshot

insert image description here

Guess you like

Origin blog.csdn.net/a6661314/article/details/124945063