linux环境下无法测试,只是把某些bug做了提示,楼主可查看下
#include<stdio.h>
#include<conio.h>
struct player
{
int number;//编号
char name[20];//姓名
float *score;
float average_score;//分数平均值
}*pp;
void sortscore(float *score, int n);//将每个人的分数排列
float score_caculation(float *score, int m);//计算平均分
int main()
{
int n = 0; //n个选手
int m = 0; //m个评委
int i, j;
char temp;
FILE *fp1, *fp2;
if ((fp1 = fopen("file1.txt", "r+")) == NULL)//打开file1.txt
{
printf("Cannot open the file1!");
getch();
return -1;
}
while (!feof(fp1))//选手个数n,评委个数m
{
temp = fgetc(fp1);
if (temp == '\n')
n++;
else if (temp == '.')
m++;
}
m /= n;
struct player *list;
list = new struct player[n];//给player分配内存
for (i = 0;i < n;++i)///////////////////////////////////////////////////m--->n
{
list[i].score = new float[m];//给player中的m个分数分配内存
}
pp = list;
rewind(fp1);
// fclose(fp1);
// if ((fp1 = fopen("file1.txt", "r+")) == NULL)//打开file1.txt
// {
// printf("Cannot open the file1!\n");
// getch();
// return -1;
// }
for (i = 0;i < n;i++, pp++)//读入数据
{
// fscanf(fp1, "%d %s", &pp->number, pp->name);
fscanf(fp1, "%d", &pp->number);
fscanf(fp1, "%s", &pp->name);
for (j = 0;j < m;j++)
{
fscanf(fp1, "%f", &pp->score[j]);
}
}
fclose(fp1);
for (i = 0;i < n;i++)//对每个选手的m个分数进行排序
sortscore(list[i].score, m);//////////////////////////////排序
for (i = 0;i < n;i++)//对每个选手的分数取平均值
list[i].average_score = score_caculation(list[i].score, m);
for (i = 0;i < n - 1;i++)//根据选手分数平均值将选手排列
{
struct player temp_player;
temp_player = list[i];
for (j = 1;j < n;j++)
{
if (list[i].average_score < list[j].average_score)
{
list[i] = list[j];
list[j] = temp_player;
}
}
}
if ((fp2 = fopen("file2.txt", "w")) == NULL)//打开file2.txt,并将数据写入file2.txt
{
printf("Cannot open file2\n");
getch();
return -1;
}
fprintf(fp2, "\t编号\t姓名\t得分\t名次\n");
for (i = 0;i < n;i++)
{
fprintf(fp2, "\t%3d\t%s\t%3f\t%d\n", list[i].number, list[i].name, list[i].average_score, i + 1);
}
fclose(fp2);
}
void sortscore(float *score, int m)//对每个选手的分数进行排序
{
float temp;
int i, j;
for (i = 0;i < m - 1;i++)
{
temp = score[i];
for (j = i + 1;j < m;j++)
{
if (score[j] < score[i])
{
temp = score[j];
score[j] = score[i];
score[i] = temp;
}
}
}
}
float score_caculation(float *score, int m)//计算每个选手的平均值
{
float sum, average;
int i;
if (m < 9)
{
for (i = 1;i < m - 1;i++)
{
sum = sum + score[i];
}
average = sum / (m - 2);
}
else
{
for (i = 2;i < m - 2;i++)
{
sum = sum + score[i];
}
average = sum / (m - 4);
}
return average;
}
|