|
发表于 2019-9-19 14:51:57
|
显示全部楼层
本帖最后由 superbe 于 2019-9-20 12:45 编辑
- #include <iostream>
- #include <fstream>
- #include <cmath>
- #include <vector>
- using namespace std;
- void calculate(vector<double>&,double&,double&,double&,double&); //函数声明
- int main() {
- vector<double> vect; //定义一个向量vect,用于存储从文件读入的数据
- double Max,Min,Mean,Var;
- size_t Elements;
- ifstream infile;
- infile.open("3B.dat");
- if(!infile){
- cout<<"fail to open the file!"<<endl;
- return -1;
- }
- double num;
- while(!infile.eof()){ //从文件中读数据到vect
- infile>>num;
- if(infile.fail()) break;
- vect.push_back(num);
- }
- Elements=vect.size(); //得到数据的数量
- calculate(vect,Max,Min,Mean,Var); //调用函数计算最大值、最小值、均值、方差
- cout<<"Elements = "<<Elements<<endl;
- cout<<"Max = "<<fixed<<Max<<endl;
- cout<<"Min = "<<Min<<endl;
- cout<<"Mean = "<<Mean<<endl;
- cout<<"Var = "<<Var<<endl;
- infile.close();
- cout<<endl;
- return 0;
- }
- /* 计算最大值、最小值、均值、方差的函数 */
- void calculate(vector<double>& v,double& max,double& min,
- double& mean,double& var){
- double sum=0,s=0; //sum是数据总和,s是sum(v[i]-mean)^2,计算方差时用到了s
- max=v[0]; //最大值
- min=v[0]; //最小值
- for(size_t i=0;i<v.size();i++){
- if(v[i]>max) //比较修改最大值
- max=v[i];
- else if(v[i]<min) //比较修改最小值
- min=v[i];
- sum+=v[i];
- }
- mean=sum/v.size(); //计算平均值
- for(size_t i=0;i<v.size();i++){
- s+=pow((v[i]-mean),2); //计算sum(v[i]-mean)^2
- }
- var=s/v.size(); //计算方差
- }
复制代码
看截图老师是要求读取文件中的double数据啊,不是整型数据?
我是在一个函数里计算四个值的,分开成四个函数每个返回一个值也可以。 |
|