BUPT-homework/semester1/pset14/2-2-struct.c

92 lines
1.6 KiB
C
Raw Permalink Normal View History

2021-12-16 17:27:53 +08:00
#include <stdio.h>
#pragma GCC optimize("Ofast,inline")
#define MAX 21
typedef struct STUDENT {
char name[MAX];
char id[MAX];
int scores[5];
float avg;
int sum;
} STUDENT;
void sort(int *arr, int n);
void GetInput(STUDENT *dude);
void print(STUDENT dude);
int main(void) {
int n;
scanf("%d", &n);
STUDENT students[n];
for (int i = 0; i < n; i++) {
getc(stdin);
GetInput(&students[i]);
}
for (int i = 0; i < n; i++) {
print(students[i]);
printf("\n");
}
return 0;
}
void sort(int *arr, int n) {
int tmp;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
if (arr[j] < arr[j + 1]) {
tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
}
void GetInput(STUDENT *dude) {
// Get name
char ch;
int loc = 0;
while ((ch = getc(stdin)) != '\n') {
dude->name[loc++] = ch;
}
dude->name[loc] = '\0';
// Get id
loc = 0;
while ((ch = getc(stdin)) != '\n') {
dude->id[loc++] = ch;
}
dude->id[loc] = '\0';
// Get scores
int sum = 0;
for (int i = 0; i < 5; i++) {
scanf("%d", &(dude->scores[i]));
sum += dude->scores[i];
}
// Populate avg and sum;
dude->sum = sum;
dude->avg = (float)sum / 5;
// We don't need to sort this time
/* sort(dude->scores, 5); */
}
void print(STUDENT dude) {
// Print answer
printf("Name:%s\n", dude.name);
printf("ID:%s\n", dude.id);
printf("Score:");
for (int i = 0; i < 4; i++) {
printf("%d ", dude.scores[i]);
}
printf("%d\n", dude.scores[4]);
printf("average:%.2f total:%d\n", dude.avg, dude.sum);
}