运行结果:
代码:
#include <stdio.h>
#include <string.h>
#define MAXSIZE 100
typedef struct _student
{
int id;
char cla[10];
char name[20];
int score;
}Student;
int main()
{
int i,j,n=0;
int sum=0;
Student stu[MAXSIZE];
char cl[MAXSIZE][10]={0};
int ave[MAXSIZE]={0};
int ps[MAXSIZE]={0};
int cln = 0; //班级数
int aa=0,bb=0,cc=0,dd=0,ee=0; //各分数段人数
FILE* fp;
fp = fopen("1.txt","r");
if(fp == 0)
{
printf("文件打开失败\n");
return 0;
}
while(!feof(fp))
{
if( fscanf(fp,"%d %s %s %d",&stu[n].id,stu[n].cla,stu[n].name,&stu[n].score))
n++;
}
fclose(fp);
//总平均成绩
fp = fopen("2.txt","w");
for(i=0;i<n;i++)
sum += stu[i].score;
sum/= n;
fprintf(fp,"all ave %d\n",sum);
//统计每个班的平均成绩
for(i=0;i<n;i++)
{
//查找班级
for(j=0;j<cln;j++)
{
if(strcmp(stu[i].cla,cl[j])==0)
break;
}
if(j<cln)
{
ave[j]+=stu[i].score;
ps[j]+=1;
}else
{
strcpy(cl[cln],stu[i].cla);
ave[cln] += stu[i].score;
ps[cln] = 1;
cln++;
}
}
//输出每个班级的平均分
for(i=0;i<cln;i++)
{
fprintf(fp,"%s ave %d\n",cl[i],ave[i]/ps[i]);
}
//统计各分数段
for(i=0;i<n;i++)
{
if(stu[i].score >=90) aa++;
else if(stu[i].score >=80) bb++;
else if(stu[i].score >= 70) cc++;
else if(stu[i].score >=60) dd++;
else ee++;
}
fprintf(fp,"90 Above:%d\n",aa);
fprintf(fp,"89-80:%d\n",bb);
fprintf(fp,"79-70:%d\n",cc);
fprintf(fp,"69-60:%d\n",dd);
fprintf(fp,"60 Below:%d\n",ee);
fclose(fp);
return 0;
}
伪代码如下
读取文件
遍历每行
分解每行数据
累加计算遍历结束后作统计
将结果写入文件