关于一道c语言的 文件操作的题目

写一个C程序,计算数据文件std0001中每一个学生的平均成绩和总成绩,结果输出到一个名为std0002.txt的数据文件中。

std0001.txt 中内容
1 2006010001 97 71 63 72 61
2 2006010002 89 59 70 98 77
3 2006010003 64 71 72 98 96
4 2006010004 61 79 73 71 89
5 2006010005 91 86 60 96 67
6 2006010006 83 76 84 87 78
7 2006010007 82 82 61 76 61
8 2006010008 79 65 84 86 94
9 2006010009 62 75 83 88 72
10 2006010010 83 78 76 73 59
11 2006010011 87 65 73 85 63
12 2006010012 67 94 91 91 90
13 2006010013 63 72 96 85 67
14 2006010014 69 90 69 78 86
15 2006010015 99 79 65 67 81
16 2006010016 73 81 99 72 83
17 2006010017 66 71 72 96 96
18 2006010018 63 68 71 85 98
19 2006010019 67 81 71 66 97
20 2006010020 95 82 70 64 88

std0002.txt 文件内容为 在std0001.txt文件的每一行 加上平均成绩和总成绩。。

数据比较多。我只弄了少量数据

#include "stdio.h"

struct SC{
char index[5]; /*序号*/
char std_n[10]; /*学号*/
int scores[5]; /*各科成绩*/
int avg_sc; /*平均成绩*/
int total_sc; /*总成绩*/

};

int main(void)
{
FILE *fp_in,*fp_out;
struct SC sc;
int i;

fp_in = fopen("std0001.txt","r"); /*打开输入文件*/
if(!fp_in)
{
printf("Can't Open the file std0001.txt\n");
exit(1);

}

fp_out = fopen("std0002.txt","wr"); /*打开输出文件*/
if(!fp_out)
{
printf("Can't Open the file std0002.txt\n");
fclose(fp_in);
exit(1);
}

while(!feof(fp_in)) /*文件尚为读完*/
{
/*从文件中读取一个学生的成绩记录*/
fscanf(fp_in,"%s %s %d %d %d %d %d",sc.index,sc.std_n,&sc.scores[0],&sc.scores[1],&sc.scores[2],&sc.scores[3],&sc.scores[4]);
sc.total_sc = 0;
for(i=0;i<5;i++) /*计算总成绩*/
{
sc.total_sc += sc.scores[i];
}

sc.avg_sc = sc.total_sc/5; /*计算平均成绩*/

/*将计算好的一个结果写入到输出文件中*/
fprintf(fp_out,"%s %s %d %d %d %d %d %d %d\n",sc.index,sc.std_n,sc.scores[0],sc.scores[1],sc.scores[2],sc.scores[3],sc.scores[4],sc.avg_sc,sc.total_sc);
}
fclose(fp_in);
fclose(fp_out);
exit(0);
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2008-11-24
楼上的如果把平均成绩改为double型,就完美了