关于文件读取 while(fgetc(fp) != EOF)
以下程序若去掉注释部份,最后一个数据就读不到,请帮修改程序程序代码:
// 从文本文件"data.txt"中取出数据,并计算平均值,方差 #include<stdio.h> #include <math.h> #define hh printf("\n=======================================\n"); void main() { FILE *fp; float x,avr,fc,a[520],sum = 0.0; int i,k = 0; fp = fopen("D:\\data.txt","r"); if(fp == NULL) { printf("文件打开失败!\n"); } else { printf("读取数据:\n"); fscanf(fp,"%f",&x); while(!feof(fp)) { a[k++] = x; printf("%.0f ",x); sum += x; fscanf(fp,"%f",&x); } /* fscanf(fp,"%f",&x); a[k++] = x; printf("%.0f ",x); sum += x; */ avr = sum / k; // k 为读到的数据个数 sum = 0; for(i = 0;i < k;i++) { sum += (a[i] - avr) * (a[i] - avr); } fc = sum / (k - 1); hh printf(" 读取个数:%d\n",k); printf(" 平 均 值:%.2f\n",avr); printf(" 方 差:%.2f\n",fc); } hh fclose(fp); }