题目描述
已知有3名学生及五门课程的成绩,要求根据学生的各科平均分排序(降序),并输出学生的所有信息和平均分(用指针数组完成)。
样例">输入样例
Jane 90 80 75 60 85
Mark 85 78 98 85 86
Lily 56 65 75 68 80
输出样例
Mark 85 78 98 85 86 86.4
Jane 90 80 75 60 85 78
Lily 56 65 75 68 80 68.8
头文件
#include<algorithm>
整形和浮点型
bool cmp(int a,int b){
return a < b;
}
int main(){
int a[10]={8 ,3 ,10 ,9 ,5};
sort(a,a+10,cmp);
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}
注意:bool cmp在int main外
sort在int main内
结构体
struct node{
char s[15];
int val;
}A[25];
bool cmp(node a,node b){
return a.val>b.val;//实现从大到小排序
}
int main(){
for(int i=0;i<3;i++){
cin>>A[i].s>>A[i].val;
}
sort(A,A+3,cmp);
for(int i=0;i<3;i++){
cout<<A[i].s<<" ";
cout<<A[i].val<<endl;
}
return 0;
}
第一 bool cmp里可用if
bool cmp(student a,student b)//定义比较规则
{
int temp = strcmp(a.name,b.name);
if(a.grade!=b.grade)
return a.grade<b.grade; //升序
else if(temp != 0)//升序 ,要做是否相等的判断
return temp<0; //此处一定要用 TEMP < 0 返回,否侧会出错,原因未知
else
return a.age < b.age;//升序
}
第二return a>b 由大到小
return a<b 由小到大
第三 sort(a,a+n,cmp) n:排几个数n为几
学到的一点 结构体的声明和定义
1. 先定义结构体类型再单独进行变量定义
struct Student
{
int Code;
char Name[20];
char Sex;
int Age;
};
struct Student Stu;
struct Student StuArray[10];
struct Student *pStru;
结构体类型是struct Student,因此,struct和Student都不能省略。
2. 紧跟在结构体类型说明之后进行定义
struct Student
{
int Code;
char Name[20];
char Sex;
int Age;
}Stu,StuArray[10],*pStu;
这种情况时,后面还可以再定义结构体变量。
3. 在说明一个无名结构体变量的同时直接进行定义
struct
{
int Code;
char Name[20];
char Sex;
int Age;
}Stu,Stu[10],*pStu;
这种情况下,之后不能再定义其他变量。