在函数中进行10个学生成绩从高到低排名 代码
时间: 2024-02-25 14:53:21 浏览: 20
好的,可以使用C++标准库中的sort函数实现。具体代码如下:
```c++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
bool cmp(int a, int b) {
return a > b; // 从大到小排序
}
void sort(vector<int>& a) {
sort(a.begin(), a.end(), cmp); // 调用sort函数进行排序
}
int main() {
vector<int> a = {90, 80, 70, 60, 50, 40, 30, 20, 10, 0};
sort(a);
for (int i = 0; i < 10; i++) {
cout << a[i] << " ";
}
return 0;
}
```
这段代码中,使用了一个自定义的比较函数`cmp`,用于指定从大到小排序。然后在`sort`函数中调用这个比较函数进行排序。最后输出排好序的数组。需要注意的是,这里使用了`vector`容器来存储成绩,因为`vector`可以动态调整容器大小,比固定大小的数组更加灵活。
相关问题
c语言在函数中进行10个学生成绩从高到低排名
好的,可以使用C语言标准库中的`qsort`函数实现。具体代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
return *(int *)b - *(int *)a; // 从大到小排序
}
void sort(int a[10]) {
qsort(a, 10, sizeof(int), cmp); // 调用qsort函数进行排序
}
int main() {
int a[10] = {90, 80, 70, 60, 50, 40, 30, 20, 10, 0};
sort(a);
for (int i = 0; i < 10; i++) {
printf("%d ", a[i]);
}
return 0;
}
```
这段代码中,使用了一个自定义的比较函数`cmp`,用于指定从大到小排序。然后在`qsort`函数中调用这个比较函数进行排序。最后输出排好序的数组。需要注意的是,这里使用了指针来传递数组,因为在C语言中,数组名本身就是指向数组首元素的指针。
在函数中进行10个学生成绩从高到低排名 sort(int a[10])代码
好的,可以使用C++标准库中的sort函数实现。具体代码如下:
```c++
#include <algorithm>
using namespace std;
bool cmp(int a, int b) {
return a > b; // 从大到小排序
}
void sort(int a[10]) {
sort(a, a + 10, cmp); // 调用sort函数进行排序
}
int main() {
int a[10] = {90, 80, 70, 60, 50, 40, 30, 20, 10, 0};
sort(a);
for (int i = 0; i < 10; i++) {
cout << a[i] << " ";
}
return 0;
}
```
这段代码中,使用了一个自定义的比较函数`cmp`,用于指定从大到小排序。然后在`sort`函数中调用这个比较函数进行排序。最后输出排好序的数组。