求平均数

来源:百度知道 编辑:UC知道 时间:2024/05/15 13:04:46
用fprent() 往文件中写入float型数据,其中每条数据一行(\r\n),然后 把数读出来求平均数,要求速度要快。

如果一次性读入内存,再做计算,要用到sscanf(),怎么做?

其中数据文件有2M左右。
注意: 这样只能读出来第一个数,后面的读不出来的

注意: 这样只能读出来第一个数,后面的读不出来的

注意: 这样只能读出来第一个数,后面的读不出来的

/*
写文件
*/

int i;
float dat[10000];
FILE *fout = fopen("out.dat", "w");
if(fout == NULL) exit(1);
for(i = 0; i < 10000; i++)
fprintf(fout, "%f", dat[i])
fclose(fout);

/*
读文件
*/

long length;
char *string;

FILE *fin = fopen("out.dat", "rb");
/* 获取文件的长度 */
fseek(fin, 0L, SEEEK_END);
length = ftell(fin);
fseek(fin, 0L, SEEK_SET);
/* 分配内存,最佳的方法是分配一定特定缓冲区内存
对文件依次读取,这里一次读完,但有可能不能分配到
足够的内存
*/
if(string = (char*)malloc(length + 1))==NULL)
{
printf("No enough memory to allocate!");
exit(1);
}
/* 将文件读完 */
fread(string, length +1, 1, fin);
fclose(fin);

float sum = 0;
float value;
int num = 0;
/* 读取字符串中的浮点数据 */
do
{
sscanf(string, "%f", &value);
sum += value
num++;
}while(!eof(string));