从图 1 所示的文件 fin.txt 中读取学生姓名、身高和体重,计算并显示它们的平均值,并且将显示结果保存到文件 fout.txt 中。
图 1:输入输出文件示例
C语言代码清单 1:读取学生姓名、身高和体重,计算并显示它们的平均值
#include
#include
int main( )
{
int num = 0;
FILE *fp1,*fp2;
char name[100];
double height,weight,hSum=0.0,wSum=0.0;
if((fp1 = fopen("fin.txt","r")) == NULL)
printf("\a文件fin.txt打开失败!\n");
else{
fp2 = fopen("fout.txt","w");
while(fscanf(fp1,"%s%lf%lf",name,&height,&weight) == 3){
printf("%-10s %5.1f %5.1f\n",name,height,weight);
fprintf(fp2,"%-10s %5.1f %5.1f\n",name,height,weight);
num++;
hSum += height;
wSum += weight;
}
printf("----------------------\n");
printf("平均 %5.1f %5.1f\n",hSum/num,wSum/num);
fprintf(fp2,"----------------------\n");
fprintf(fp2,"平均 %5.1f %5.1f\n",hSum/num,wSum/num);
fclose(fp1); fclose(fp2);
}
system("pause");
return 0;
}
运行结果为:
Linda 155.0 40.5
Mary 157.0 39.5
Tony 150.0 38.3
Sala 158.0 42.8
———————-
平均 155.0 40.3