c++如何用数组给成绩排名
时间: 2023-06-08 13:08:46 浏览: 139
对于如何用数组给成绩排名,我可以给您提供一种简单的方法。首先,需要定义一个成绩数组,存放每个学生的成绩。然后,使用一个循环,对成绩数组进行排序(可以使用快速排序等算法),得到各个学生的排名。同时,还需要定义一个名字数组,与成绩数组一一对应,以便在输出排名时能够同时输出每个学生的名字。以下是示例代码:
```c
#include <stdio.h>
#define NUM_STUDENTS 5
int main() {
char names[NUM_STUDENTS][20] = {"Alice", "Bob", "Charlie", "David", "Emily"};
int scores[NUM_STUDENTS] = {80, 90, 70, 85, 95};
int temp_score, temp_rank;
// sort scores and get ranks
for (int i = 0; i < NUM_STUDENTS - 1; ++i) {
for (int j = i + 1; j < NUM_STUDENTS; ++j) {
if (scores[j] > scores[i]) {
// swap scores
temp_score = scores[i];
scores[i] = scores[j];
scores[j] = temp_score;
// swap names
char temp_name[20];
strcpy(temp_name, names[i]);
strcpy(names[i], names[j]);
strcpy(names[j], temp_name);
}
}
}
// output ranking
for (int i = 0; i < NUM_STUDENTS; ++i) {
temp_rank = i + 1;
printf("%d.\t%s\t%d\n", temp_rank, names[i], scores[i]);
}
return 0;
}
```
在上面的示例代码中,我们使用了冒泡排序来对成绩数组进行排序,同时也需要对名字数组进行相应的交换操作。排序完成后,我们可以依次输出每个学生的排名、名字和成绩。