gpt4 book ai didi

c++ - 从文本文件读入 vector

转载 作者:太空宇宙 更新时间:2023-11-04 14:38:11 25 4
gpt4 key购买 nike

我很难理解为什么我的代码不起作用。有问题的部分是当我将值从我的文本文件传递到我的成绩变量时。我不明白为什么这是错误的。除此以外,我的代码的其他一切都很好,但无论如何我都包含了它。

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();
}

我觉得自己像个白痴,因为我不明白为什么这不起作用......我应该能够弄清楚,但我没有。

最佳答案

C++ 遵循先例的正常数学顺序。

这一行:

sum=sum+(vecx[i]-average*vecx[i]-average);

看起来不正确。乘法发生在减法之前,所以它正在计算:

sum=sum+((vecx[i]-(average*vecx[i]))-average);

但大概你的意思是:

sum=sum+((vecx[i]-average)*(vecx[i]-average));

您可能有兴趣查看 the full list of precedence ordering .

关于c++ - 从文本文件读入 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14837484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com