问题的提出:某大学开田径运动会,现有12名选手参加100米比赛,对应的运动员号及成绩如表所示,请按照成绩排名并输出,要求每一行输出名次、运动员号及成绩。要求用冒泡法排序。
运动员号
|
成绩(秒)
|
运动员号
|
成绩(秒)
|
001
|
13.6
|
031
|
14.9
|
002
|
14.8
|
036
|
12.6
|
010
|
12.0
|
037
|
13.4
|
011
|
12.7
|
102
|
12.5
|
023
|
15.6
|
325
|
15.3
|
025
|
13.4
|
438
|
12.7
|
把数据写入a.txt中。
然后从a.txt中输出数据 ,进行排序,然后写入b.txt中。
///////////////a.txt/////////////////
/////////////////////////////////
001 13.6
002 14.8
010 12.0
011 12.7
023 15.6
025 13.4
031 14.9
036 12.6
037 13.4
102 12.5
325 15.3
438 12.7
//////////order.h/////////
/////////////////////////////
#include
#include
using namespace std;
struct Player
{
char num[3];
float score;
};
class Order
{
protected:
Player *player;
FILE *fp1,*fp2;
int i,j;
public:
Order(FILE *f1,FILE *f2);
Order(const Order& s);
Order& operator=(Order& s);
void write(FILE *);
void bubble();
~Order()
{
delete [] player;
player=NULL;
}
};
/////////order.cpp//////////
//////////////////////////////////////////
#include"order.h"
Order::Order(FILE *f1,FILE *f2):i(0),j(0)
{
fp1=f1;
fp2=f2;
player=new Player[12];
while(fscanf(f1,"%s %f\n",&((player+i)->num),&((player+i)->score))!=EOF)
{i++;}
}
Order::Order(const Order& s):j(0)
{
fp1=s.fp1;
fp2=s.fp2;
i=s.i;
player=new Player[12];
if(player)
{
memcpy(player,s.player,12*sizeof(Player));
}
}
void Order::bubble()
{
Player temp;
for(int line=i;line>1;line--)
for(int j=0;j {
if(((player+j)->score)>((player+j+1)->score))
{
memcpy(&temp,player+j,sizeof(Player));
memcpy(player+j,&player[j+1],sizeof(Player));
memcpy(player+j+1,&temp,sizeof(Player));
}
}
}
void Order::write(FILE *p)
{
/*for(int k=0;k {
cout<<(*(player+k)).num<<' '<<(*(player+k)).score< }
*/
for(j;j{
fprintf(p,"%s %.1f\n",(player+j)->num,(player+j)->score);
}
}
Order& Order::operator=(Order& s)
{
if(this == &s)return s;
delete [] player;
player=new Player[12];
if(player)
{
memcpy(player,s.player,12*sizeof(Player));
}
return *this;
}
//////////paiming.cpp/////////
////////////////////////////////////////////
#include"order.h"
int main(int argc,char* argv[])
{FILE *f1,*f2;
if((f1=fopen(argv[1],"r"))==NULL)
{
cout<<"can not open"<<' '<
}
if((f2=fopen("b.txt","w")) == NULL)
{
cout<<"can not open b.txt"< }
Order a(f1,f2);
Order b=a;
b.bubble();
b.write(f2);
fclose(f1);
fclose(f2);
}
///////////////////Makefile///////////////
////////////////////////////////////////
CC=g++
paiming:paiming.o order.o
order.o: order.h
paiming.o:order.h
$(CC) -c paiming.cpp
.PHONY:clean
clean:
-rm -f paiming *.o
/////////////运行结果:b.txt/////////////
/////////////////////////
010 12.0
102 12.5
036 12.6
011 12.7
438 12.7
025 13.4
037 13.4
001 13.6
002 14.8
031 14.9
325 15.3
023 15.6
感谢赵启先生的指导!
阅读(1481) | 评论(0) | 转发(0) |