Meanand Standard Deviation-从文件中读取数据计算其平均数和标准差

//Meanand Standard Deviation-从文件中读取数据计算其平均数和标准差
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<cmath>
 
int main()
{
    usingnamespace std;
    ifstream fin;
    ofstream fout;
 
    double aver,tem,count =0,sum = 0;
    double stadev;
 
    fin.open("numbers.dat");
    if(fin.fail())
    {
        cout<<"Input file opening failed.\n";
        exit(1);
    }
 
    //fin>>tem;
    //sum = tem;
    while(fin>>tem)
    {
        count++;
        sum += tem;
    }
 
    cout<<"sum ="<<sum<<endl;
    cout<<"count = "<<count<<endl;
    aver = sum/count;
 
    fin.close();
 
    fin.open("numbers.dat");
    if(fin.fail())
    {
        cout<<"Input file opening failed.\n";
        exit(1);
    }
 
    sum  =0;
    fin>>tem;
    while(!fin.eof())
    {
        sum += (tem - aver)*(tem - aver);
        fin>>tem;
    }
 
    stadev = sqrt(sum / count);
 
    cout<<"The average is "<<aver<<endl;
    cout<<"The stadev is "<<stadev<<endl;
 
    fin.close();
    return 0;
}

文件1:

1 2 3 4 5 6

结果1:

sum=21
count= 6
Theaverage is 3.5
The stadev is1.36931

文件2:

8 8 8 8 8 8

结果2:

sum=48
count= 6
Theaverage is 8
The stadev is 0

文件3:

11.2 1.3 2.4 8.5 7.6 3.7 4.8 6.9 5.0 9.1

结果3:

sum=60.5
count= 10
Theaverage is 6.05
The stadev is 2.9837