最近做一个大赛评分的小程序,使用面向对象方式做的,代码如下:
#include <iostream>
#include <cstring>
using namespace std;
const unsigned JudgeNum = 5;
const unsigned PlayerNum = 5;
class CompetitionResult
{
short num; //选手号码
char name[10]; //选手姓名
float score[JudgeNum]; //记录各评委给选手的打分
float average; //选手最后得分,去掉一个最高分和一个最低分的平均得分
public:
CompetitionResult(); //无参构造函数
CompetitionResult(short n,char* ps); //一般构造函数
float MaxScore(); //求评委打的最高分
float MinScore(); //求评委打的最低分
void SavAvg(); //求选手最后得分
float GetAvg()
{
return average; //读选手最后得分
}
short GetNo()
{
return num; //读选手的编号
}
void SetNo(int i)
{
num=i; //设置选手的编号
}
void SetName(char* p) //设置选手姓名
{
strcpy(name,p);
}
char* GetName()
{
return name; //读选手的姓名
}
float GetScore(int j)
{
return score[j-1]; //读第j个评委的打分
}
void SetScore(int k,float av)
{
score[k-1]=av; //记录第K个评委的打分
}
friend void Sort(CompetitionResult* pr,int n); //按最后得分由高到低排序
};
CompetitionResult::CompetitionResult()
{
}
CompetitionResult::CompetitionResult(short n,char* ps)
{
num=n;
strcpy(name,ps);
for(int i=0;i<JudgeNum;i++)
score[i]=0.0;
}
float CompetitionResult::MaxScore()
{
unsigned i,j;
for(i=0; i<JudgeNum; i++)
for(j=0; j<JudgeNum-i; j++)
if(GetScore(j)>GetScore(j+1))
{
score[j-1]+=score[j];
score[j]=score[j-1]-score[j];
score[j-1]=score[j-1]-score[j];
}
return score[JudgeNum-1];
}
float CompetitionResult::MinScore()
{
unsigned i,j;
for(i=0; i<JudgeNum; i++)
for(j=0; j<JudgeNum-i; j++)
if(GetScore(j)>GetScore(j+1))
{
score[j-1]+=score[j];
score[j]=score[j-1]-score[j];
score[j-1]=score[j-1]-score[j];
}
return score[0];
}
void CompetitionResult::SavAvg()
{
int i;
float sum=0.0;
for(i=1; i<=JudgeNum; i++)
sum+=GetScore(i);
sum=sum-MaxScore()-MinScore();
average=sum/(JudgeNum-2);
}
void Sort(CompetitionResult* pr,int n)
{
int i,j;
CompetitionResult temp;
for(i=0;i<n-1;i++)
for(j=0;j<n-1-i;j++)
if(pr[j].GetAvg()<pr[j+1].GetAvg())
{
temp=pr[j];
pr[j]=pr[j+1];
pr[j+1]=temp;
}
cout<<n<<"个选手排名为:"<<endl;
for(i=0; i<n-1; i++)
{
cout<<"第"<<i+1<<"名:";
cout<<"选手"<<pr[i].num<<"号,";
cout<<"姓名"<<pr[i].GetName()<<",";
cout<<"得分"<<pr[j].average<<endl;
}
}
int main()
{
CompetitionResult pr[PlayerNum];
unsigned i,j;
float scorein=0.0;
char p[10]="Noname";
//CompetitionResult();
/*for(i=0;i<PlayerNum;i++)
CompetitionResult pr[i](0,p);*/
for(i=0; i<PlayerNum;i++)
{
cout<<"请输入第"<<i+1<<"位的姓名(不超过10个字符):"<<endl;
cin>>p;
pr[i].SetName(p);
cout<<"请为第"<<i+1<<"位选手打分: "<<endl;
pr[i].SetNo(i+1);
for(j=0;j<JudgeNum;j++)
{
cin>>scorein;
pr[i].SetScore(j+1,scorein);
}
}
cout<<"***********************"<<endl;
for(j=0; j<PlayerNum; j++)
{
cout<<"编号"<<j+1<<endl;
cout<<"最高分:";
cout<<pr[j].MaxScore()<<endl;
cout<<"最低分:";
cout<<pr[j].MinScore()<<endl;
cout<<"平均分:";
pr[j].SavAvg();
cout<<pr[j].GetAvg()<<endl;
cout<<"***********************"<<endl;
}
Sort(pr,PlayerNum);
return 0;
}
但是在编译运行后,排名时的平均分和求出来的平均分不一样,我不知道是不是交换值后原有的average被冲掉了,大家看看出错在什么地方。谢谢!