コードが機能しない理由を理解するのに苦労しています。問題になるのは、テキスト ファイルから成績変数に値を渡すときです。なぜこれが間違っているのかわかりません。それを除いて、私のコードの他のすべては問題ありませんが、とにかくすべて含めました。
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();
}
これがうまくいかない理由がわからないのは馬鹿みたいです...私はこれを理解できるはずですが、まだ理解していません。