我很难理解为什么我的代码不起作用。有问题的部分是当我将文本文件中的值传递到我的等级变量时。我不明白为什么这是错误的。除此以外,我的代码中的其他所有内容都很好,但无论如何我都包含了它。
string fileName;
cout << "Program that takes data from file and calculate\nmean and standard deviation and put it in file out.txt\n";
cout << "Enter the input file name ";
cin >> fileName;
double grade;
ifstream inData;
inData.open(fileName.c_str());
// Declare vector<double> vecx
vector<double> vecx;
// read data from input file to vector vecx,
while(inData >> grade)
{
vecx.push_back(grade);
}
inData.close();
// keep track how many elements you read from file
// When you done with reading from file, close stream inData
如果您有兴趣,这里是完整的代码。
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
using namespace std;
int main()
{
string fileName;
cout << "Program that takes data from file and calculate\nmean and standard deviation and put it in file out.txt\n";
cout << "Enter the input file name ";
cin >> fileName;
double grade;
ifstream inData;
inData.open(fileName.c_str());
// Declare vector<double> vecx
vector<double> vecx;
// read data from input file to vector vecx,
while(inData >> grade)
{
vecx.push_back(grade);
}
inData.close();
// keep track how many elements you read from file
// When you done with reading from file, close stream inData
// read element by element in vector vecx and calculate sum;
double sum=0;
double average;
for (int i=0; i < vecx.size(); i++)
sum=sum+vecx[i];
average=sum/(vecx.size());
// sum divide by number of elements to find mean(average)
//again read element by element and calculate
//square of difference between element and mean
//calculate sum of squares of differences
//divide by number of elements and
//take square root - you got the standard deviation
sum=0;
double variance, stdev;
for (int i=0; i < vecx.size(); i++)
sum=sum+(vecx[i]-average*vecx[i]-average);
variance=sum/(vecx.size());
stdev=sqrt(variance);
//open output stream
ofstream outData;
outData.open("out.txt");
//output mean and standard deviation
cout << "Average is " << average << endl;
cout << "Standard deviation is " << stdev << endl;
//close stream
outData.close();
}
我觉得自己像个白痴,因为我不明白为什么这不起作用……我应该能够弄清楚,但我没有。