1.本地文件数据如下
2.要求求出B开头(男生)后面的数字的平均数(男生年龄);G(女生)后面数字平均数(女生年龄);以及所有数字平均数;
3.思路:按行读取,判断开头字母,分类求和求平均数。
4.代码如下:
#include<stdio.h>
#include<stdlib.h>
int main(){
int i=0,j=0;
double sum1=0,sum2=0,a;
char c;
FILE *fp;
fp=fopen("a.txt","r");
if(fp==NULL){
printf("File open error!\n");
return 0;
}
while(!feof(fp)){
fscanf(fp,"%c%lf\n",&c,&a);
if(c=='B'){
i++;
sum1=sum1+a;
}
if(c=='G'){
j++;
sum2=sum2+a;
}
}
printf("the average of boys is %.2lf\n",sum1/i);
printf("the average of girls is %.2lf\n",sum2/j);
printf("the average of total is %.2lf\n",(sum1+sum2)/(i+j));
fclose(fp);
return 0;
}
总结:
1.可以用数组存储数字年龄,实现对年龄排序问题。
2.注意细节,fscanf函数的使用,后面要加\n,如果文本中有空格函数中也要空格;还有按格式输出的两位小数,加上.2lf控制格式输出。