| 网站首页 | 业界新闻 | 小组 | 交易 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛

```// 从文本文件"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);
}
```

```#include <stdio.h>

int main( void )
{
FILE* fp = fopen("D:\\data.txt","r");
if(fp == NULL)
{
printf("文件打开失败!\n");
return 1;
}

puts( "读取数据：" );
size_t k = 0;
float sum=0.0f, sum2=0.0f;
for( float x; fscanf(fp,"%f",&x)==1; ++k )
{
sum2 += x*x;
sum += x;
printf( "%.0f ", x );
}
fclose( fp );

puts( "\n=======================================" );
float avr = sum / k;
float fc = (sum2 - sum*sum/k)/(k-1);
printf("  读取个数：%d\n",k);
printf("  平 均 值：%.2f\n",avr);
printf("  方    差：%.2f\n",fc);
}
```

• 7
• 1/1页
• 1

Powered by Discuz, Processed in 0.057285 second(s), 8 queries.