帮我写一个在主函数中输入18个学生的成绩,从分数从高到底进行排序的代码
时间: 2023-06-19 12:03:13 浏览: 48
好的,以下是一个示例代码:
```
#include <stdio.h>
#define NUM_STUDENTS 18
void sortDescending(int array[], int length);
int main()
{
int scores[NUM_STUDENTS];
// Input scores
printf("Enter the scores of %d students:\n", NUM_STUDENTS);
for (int i = 0; i < NUM_STUDENTS; i++)
{
printf("Student %d: ", i + 1);
scanf("%d", &scores[i]);
}
// Sort scores in descending order
sortDescending(scores, NUM_STUDENTS);
// Print sorted scores
printf("\nSorted scores in descending order:\n");
for (int i = 0; i < NUM_STUDENTS; i++)
{
printf("%d\n", scores[i]);
}
return 0;
}
void sortDescending(int array[], int length)
{
for (int i = 0; i < length - 1; i++)
{
for (int j = i + 1; j < length; j++)
{
if (array[j] > array[i])
{
// Swap elements
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
```
这个代码通过定义一个 `scores` 数组来存储输入的成绩,然后使用 `sortDescending` 函数对 `scores` 数组进行排序,最后输出排序后的结果。`sortDescending` 函数使用冒泡排序算法,从大到小比较相邻的两个元素,如果后一个元素比前一个元素大,则交换它们的位置。
希望能对你有所帮助。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)