|||
读取二进制文件中的数据,并计算最大值、最小值以及均值
#include <fstream>
#include <stdlib.h>
void main()
{
//将数据写入二进制文件中
char *f1path = "C:\Users\linqy\Desktop\ex1.dat";//文件的路径
ifstream ifstr(f1path,ios::in | ios::_Nocreate | ios::binary);
if (!ifstr)
{
cerr<<"file open failed!"<<endl;
exit(1);
}
int xx,min,max,n = 0;
float mean;
//ifstr.seekg(0);//将文件指针移至文件开始的位置
//if (ifstr.read((char*)&xx,sizeof(int)))
//{
// n++;
//}
//else
//{//若文件为空,则返回
// cerr<<"file is null "<<endl;
// exit(1);
//}
//min = max = xx;
//mean = (float)xx;
//while (!ifstr.eof())
//{
// if (ifstr.read((char*)&xx,sizeof(int)))
// {
// n++;
// if (xx > max)
// {
// max = xx;
// }
// else if (min > xx)
// {
// min = xx;
// }
// mean += xx;
// }
//}
//mean /= n;
ifstr.seekg(0,ios::end);//将文件指针移至文件尾
int nn = ifstr.tellg()/sizeof(int);//按整形大小计算的文件长度
if (nn == 0)
{
cerr<<"the file entered is null !"<<endl;
exit(1);
}
ifstr.seekg(0);//将文件指针移至文件开始的位置
ifstr.read((char*)&xx,sizeof(int));//读取第一个数到xx
min = max = xx;
mean = (float)xx/nn;
for (size_t i = 1;i < nn; i++ )
{
ifstr.read((char*)&xx,sizeof(int));
if (xx > max)
{
max = xx;
}
else if (xx < min)
{
min = xx;
}
mean += (float) xx/nn;//这个计算均值的方法不错!
}
cout<<"min = "<<min<<endl;
cout<<"max = "<<max<<endl;
cout<<"mean = "<<mean<<endl;
cout<<"Action finished!"<<endl;
system("pause");
}
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-9-27 11:48
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社