//使用交换排序法,利用指针和数组对学生成绩进行升序排序 #include <stdafx.h> #include <iostream> #include <stdlib.h> #include <cmath> #include <iomanip> using namespace std; struct student { int no; char name[10]; char sex; double score; }; void sort(student *s[],int n) { struct student *stumin; for (int i=0;i<n;i++) { for (int j=i+1;j<n;j++) { if((*s[i]).score > (*s[j]).score) { stumin = s[j]; s[j] = s[i]; s[i] = stumin; } } } } #define length 6 void main() { struct student stu[5]={{1,"zhao",'M',87.5},{2,"qian",'M',60.8},{3,"sun",'F',96.2},{4,"li",'M',77.8},{5,"zhou",'F',37.6}}; cout<<"使用结构体变量名:"<<endl; cout <<setw(4)<<"NO."<<setw(8)<<"姓名"<<setw(8)<<"性别"<<setw(8)<<"年龄"<<endl; for (int i=0;i<5;i++) { cout <<setw(4)<<stu[i].no<<setw(8)<<stu[i].name<<setw(8)<<stu[i].sex<<setw(8)<<stu[i].score<<endl; } cout<<"使用结构体数组指针:"<<endl; struct student *s[5]; for (int i=0;i<5;i++) { s[i] = &stu[i]; } cout <<setw(4)<<"NO."<<setw(8)<<"姓名"<<setw(8)<<"性别"<<setw(8)<<"年龄"<<endl; for (int i=0;i<5;i++) { cout <<setw(4)<<(*s[i]).no<<setw(8)<<(*s[i]).name<<setw(8)<<(*s[i]).sex<<setw(8)<<(*s[i]).score<<endl; } cout<<"使用算法交换排序法:"<<endl; struct student *p[5]; for (int i=0;i<5;i++) { p[i] = &stu[i]; } sort(p,5); cout <<setw(4)<<"NO."<<setw(8)<<"姓名"<<setw(8)<<"性别"<<setw(8)<<"年龄"<<endl; for (int i=0;i<5;i++) { cout <<setw(4)<<(*p[i]).no<<setw(8)<<(*p[i]).name<<setw(8)<<(*p[i]).sex<<setw(8)<<(*p[i]).score<<endl; } }