【C语言】15_实现学生结构体,求最高分学生 & 课程平均分 & 按总分排序输出

#include<stdio.h>
#include<stdbool.h>

#define N 20
#define STULEN 5
#define COURSELEN 3

#define SWAP(arr, i, j) {	\
	struct Student* t = arr[i];	\
	arr[i] = arr[j];	\
	arr[j] = t;	\
}

typedef struct {
	int id;
	char name[N];
	int chinese;
	int math;
	int english;
}Student;

void course_average(Student* s[], int stulen) {
	double sum[COURSELEN] = { 0 };
	for (int i = 0; i < COURSELEN; i++) {
		for (int j = 0; j < stulen; j++) {
			if (i == 0) sum[i] += s[j]->chinese;
			else if (i == 1) sum[i] += s[j]->math;
			else if (i == 2) sum[i] += s[j]->english;
		}
	}
	for (int i = 0; i < COURSELEN; i++) {
		printf("%.2lf ", sum[i] / stulen);
	}
	printf("\n");
}

int total_score(Student* s) {
	return s->chinese + s->math + s->english;
}

void sort_stu(Student* s[], int len) {
	//冒泡排序
	for (int i = 0; i < len - 1; i++) {
		bool flag = true;
		for (int j = 0; j < len - i - 1; j++) {
			if (total_score(s[j]) < total_score(s[j + 1])) {
				flag = false;
				SWAP(s, j, j + 1);
			}
		}
		if (flag) break;
	}
}

void print_stu(Student* s[], int len) {
	for (int i = 0; i < len; i++) {
		printf("%d %s %d %d %d\n",
			s[i]->id, s[i]->name,
			s[i]->chinese, s[i]->math, s[i]->english);
	}
	printf("\n");
}

int main(void) {
	Student stu[STULEN];
	for (int i = 0; i < STULEN; i++) {
		scanf("%d%s %d%d%d",
			&stu[i].id,
			stu[i].name,
			&stu[i].chinese,
			&stu[i].math,
			&stu[i].english);
	}
	//Student* pstu[STULEN] = { stu, stu + 1, stu + 2, stu + 3, stu + 4 };
	Student* pstu[STULEN];
	for (int i = 0; i < STULEN; i++) {
		pstu[i] = &stu[i];
	}

	sort_stu(pstu, STULEN);
	printf("\n");

	//最高分学生
	printf("The student with the highest score is: ");
	print_stu(pstu, 1);
	printf("\n");

	//课程平均分
	printf("The average score for each course is: ");
	course_average(pstu, STULEN);
	printf("\n");

	//排序输出
	print_stu(pstu, STULEN);

	return 0;
}

/*
1 cat 100 100 100
2 dog 90 91 92
3 frog 57 58 59
4 pig 80 81 82
5 rabbit 85 86 87
*/
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值