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

2024-11-17 20:48:57
推荐回答(2个)
回答1:

#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);
}

回答2:

楼上的如果把平均成绩改为double型,就完美了