您的位置:首页 > 其它

读取文件中的数据,并且计算其平均值和标准偏差

2010-12-21 18:59 471 查看
#include <fstream>
#include <string>
#include <assert.h>
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
int main(int argc, char* argv[])
{
double data;
vector<double> Vdata;           // file contains an undermined number of integer values
ifstream fin;     // declare stream variable name
fin.open(argv[1]/*"D://test//1.txt/0"*/,ios::in);    // open file
assert (!fin.fail());
fin >> data;        // get first number from the file (priming the input statement)
// You must attempt to read info prior to an eof( ) test.
while (!fin.eof( ))      //if not at end of file, continue reading numbers
{
Vdata.push_back(data);
cout<<data<<endl;    //print numbers to screen
fin >> data;               //get next number from file
}
fin.close( );       //close file
double sum=0;
int count=0;
for (vector<double>::iterator itr=Vdata.begin();itr!=Vdata.end();++itr)
{
++count;
sum+=*itr;
}
double avg=sum/count;
//cout<<avg<<endl;
double stdDev2=0;
double stdDev=0;
for (vector<double>::iterator itr=Vdata.begin();itr!=Vdata.end();++itr)
{
stdDev2+=pow((*itr-avg),2);
}
stdDev=sqrt(stdDev2/(count-1));
cout<<"Average="<<avg<<"  "<<"Standard Deviation="<<stdDev<<endl;
cout<<"Relative Standard Deviation="<<stdDev/avg*100<<"%"<<endl;

return 0;

}
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐