⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 stru_sort02.cpp

📁 数据结构常用算法合集
💻 CPP
字号:
//stru_sort02.cpp					结构数组排序
#include <iostream.h>				//cout,cin
#include <stdlib.h>				//random()
#include <string.h>				//strlen()
#include <iomanip.h>				//setw()
#include <conio.h>				//getch()
const short N=10;
const char *title="座号 语文 英语 数学 总分 平均   名次\n";
struct rec
{ short seat;					//座号
  int chi,eng,math,total;
  float ave;
  short rank;					//名次
};
//prototype
void get_data(rec*,int);			//取得数据
void list_line(int,char);			//输出分隔线
void list_title(char*);			//输出标题
void output_data(rec*);			//指针传递
void swap_rec(rec&, rec&);			//地址别名
void main()
{ rec student[10];
  short i,j;
  for (i=0;i<N;i++)
  get_data(&student[i],i);			//调用函数取得数据
  //打印排序前数据
  list_title("前):\n"); 			//打印标题
  for (i=0;i<N;i++)
  output_data(&student[i]);			//输出数组
  list_line(strlen(title)-1,'=');		//输出下划线
  cout <<"\n";
  //依总分total排序由大到小
  for (i=0;i<N-1;i++)
  for (j=0;j<N-i-1;j++)
  if (student[j].total < student[j+1].total)
  swap_rec(student[j],student[j+1]);	//交换结构
  //写名次1,2,3,...10 到rank字段
  for (i=0;i<N;i++)
  student[i].rank = i+1;
  //依座号seat排序由小到大
  for (i=0;i<N-1;i++)
  for (j=0;j<N-i-1;j++)
  if (student[j].seat > student[j+1].seat)
  swap_rec(student[j],student[j+1]);	//交换结构
  //打印排序后数据
  list_title("后):\n");
  for (i=0;i<N;i++)
  output_data(&student[i]);
  list_line(strlen(title)-1,'=');
  cout <<"\n";
  getch();
}	//end of main()
//get_data
void get_data(rec *a,int i)
{ a->seat=i+1;					//指针方式
  a->chi=random(101);				//随机数分数
  a->eng=random(101);
  a->math=random(101);
  a->total=a->chi+a->eng+a->math;		//总分
  a->ave=a->total/3.0;				//求平均
  a->rank = 0;					//名次
}
//list_line
void list_line(int n,char ch)
{ for (int i=0;i<n;i++)
  cout << ch;					//输出字符
  cout << endl;
}
//list_title
void list_title(char *str)
{
  cout << "学生的成绩(排序"<<str;
  list_line(strlen(title)-1,'-');
  cout <<title;					//输出各字段名称
  list_line(strlen(title)-1,'=');
}
//output_data
void output_data(rec *a)
{ cout << setw(3) << a->seat;
  cout << setw(5) << a->chi;
  cout << setw(5) << a->eng;
  cout << setw(5) << a->math;
  cout << setw(5) << a->total;
  cout << setw(8) << a->ave;
  cout << setw(5) << a->rank<<"\n";
}
  //swap_rec
  void swap_rec(rec &a, rec &b)
  { rec t;
    t = a;						//互换结构
    a = b;
    b = t;
  }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -