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

📄 stru_sort01.cpp

📁 数据结构常用算法合集
💻 CPP
字号:
//stru_sort01.cpp						结构数组排序
#include <iostream.h>					//cout,cin
#include <stdlib.h>					//random()
#include <iomanip.h>					//setw()
#include <conio.h>					//getch()
const short N=10;
struct rec
{ short seat;						//座号
  int chi,eng,math,total;
  float ave;
  short rank;						//名次
};
void main()
{ rec student[N];
  short i,j;
  for (i=0;i<N;i++)
  { (student+i)->seat=i+1;				//指针方式
    student[i].chi=random(101);			//随机数分数
    (student+i)->eng=random(101);
    (student+i)->math=random(101);
    
(student+i)->total=(student+i)->chi+(student+i)->eng+(student+i)->math;
    (student+i)->ave=(student+i)->total/3.0;	//求平均
    student[i].rank = 0;
  }
  cout << "学生的成绩(排序前):\n";
  cout <<"座号 语文 英语 数学 总分 平均\n";		//输出各字段分数
  for (i=0;i<N;i++)
  { cout<<setw(3)<<student[i].seat;
    cout<<setw(5)<<(student+i)->chi;
    cout<<setw(5)<<(student+i)->eng;
    cout<<setw(5)<<(student+i)->math;
    cout<<setw(5)<<(student+i)->total;
    cout<<setw(8)<<(student+i)->ave<<"\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)
  { rec t;
    t = student[j];
    student[j] = student[j+1];
    student[j+1] = t;
  }
  //写名次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)
  { rec t;
    t = student[j];
    student[j] = student[j+1];
    student[j+1] = t;
  }
  cout << "学生的成绩(排序后):\n";
  cout <<"------------------------------------\n";
  cout <<"座号 语文 英语 数学 总分 平均   名次\n";	//输出各字段分数
  cout <<"====================================\n";
  for (i=0;i<N;i++)
  { cout<<setw(3)<<student[i].seat;
    cout<<setw(5)<<(student+i)->chi;
    cout<<setw(5)<<(student+i)->eng;
    cout<<setw(5)<<(student+i)->math;
    cout<<setw(5)<<(student+i)->total;
    cout<<setw(8)<<(student+i)->ave;
    cout<<setw(5)<<(student+i)->rank<<"\n";
  }
  cout <<"==================================\n";
  getch();
}

⌨️ 快捷键说明

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