在你的代码中,计算每个学生的平均成绩没有问题。但是在排序的部分,你使用了冒泡排序来将成绩最高的学生排在最前面,这是有问题的。因为你只是交换了平均成绩,实际上应该同时交换整行数据。
下面是修改后的代码,我使用了标准库函数qsort来进行排序:#include <stdio.h>#include <stdlib.h>int compare(const void *a, const void *b) { float avgA = *((float*)a + 4); float avgB = *((float*)b + 4); return avgA > avgB ? -1 : 1;}int main() { float a[5][5] = { {10, 30, 40, 80, 0}, {10, 20, 80, 80, 0}, {50, 20, 80, 70, 0}, {82, 65, 87, 98, 0}, {100, 100, 100, 100, 0} }; for (int i = 0; i < 5; i++) { for (int j = 0; j < 4; j++) { a[i][4] += a[i][j]; if (j == 3) a[i][4] = a[i][4] / 4.0; } } printf("排序前::\n"); for (int i = 0; i < 5; i++) { printf("第%d个学生的平均成绩是%f\n", i + 1, a[i][4]); } qsort(a, 5, sizeof(a[0]), compare); printf("排序后::\n"); for (int i = 0; i < 5; i++) { printf("第%d个学生的平均成绩是%f\n", i + 1, a[i][4]); } return 0;}
在修改后的代码中,我定义了一个compare函数用于qsort排序的比较。然后在主函数中调用qsort对数组进行排序。这样就能正确地将成绩最高的学生排在最前面,成绩最低的学生排在数组最后面。 |