如何使用C ++从data.txt文件中获取平均值?

时间:2019-03-03 04:56:32

标签: c++ file vector average

我们的教授希望我们修复用于对data.txt文件中的值数量进行计数并计算其平均值的代码。这是代码:

#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
#include <vector>

using namespace std;

int main(int argc, char *argv[])
{
  string s;
  ifstream f;
  int nItems;
  double * data;
  double sum=0;
  vector < double > data2;
  double item;

  cout <<"File name: ";
  cin >> s;  
  f.open (s.c_str() );

  while (! f.eof() )
  {
    f >> item;
    data2.push_back(item);  
  }

  for (int i =0; i < nItems; i++)
  {
    sum += data[i];  
  }    
  cout << "The average is " << sum/nItems <<".\n";


    cout << "Press the enter key to continue ...";
    cin.get();
    return EXIT_SUCCESS;
}

他的指示是:<​​/ p>

  

修改代码已在当今使用,以便正确计算vector 数据中的数据平均值。现在,代码只为您提供了一个不是平均值的值。

我尝试将nItems变量更改为12,这似乎可行,但是代码的目标是确定nItems并使用它来找到平均值,我似乎无法弄清楚。

2 个答案:

答案 0 :(得分:0)

您使用data进行汇总时尚未分配任何内存,这将导致未定义的行为。您已将值存储在data2中。删除不需要的变量。另外,using namespace std is considered bad practice

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <numeric> // std::accumulate

int main(int, char**) {
    std::string filename;

    std::cout << "File name: ";
    std::cin >> filename;
    std::ifstream f(filename); // no need for .c_str()

    std::vector<double> data;
    double item;

    // instead of checking for eof, check if extraction succeeds:
    while(f >> item) {
        data.push_back(item);
    }

    // a standard way to sum all entries in a container:
    double sum = std::accumulate(data.begin(), data.end(), 0.);

    std::cout << "The sum is " << sum << "\n";

    // use the containers size() function. it returns the number of items:
    std::cout << "The average is " << (sum / data.size()) << "\n";
}

答案 1 :(得分:-2)

嘿,您似乎没有从txt文件中读取数字。 在这里,我只浏览输入文件一次,以计算有多少个数字 这样我就可以制作数组。 然后我再次浏览以填充数组。

#include <cstdlib> 
#include <iostream> 
#include <fstream> 
// f here stands for find, fstream gives you files

using namespace std;

int main(int argc, char *argv[]) {
    string s; 
    ifstream f; 
    // input file stream
    int nItems; 
    double * data; 
    double sum=0;

    cout << "File name: "; 
    cin >> s; 
    f.open (s.c_str() );
    // s.c_str will return a char array equivalent of the string s
    nItems=0;
    int input =0;
    while (f >> input) {//first loop reading through file to count number of items
        nItems++;
    }
    f.close();
    data = new double[nItems]; //Make the array
    f.open (s.c_str() );//open file for second read
    int i=0;
    while (f >> input) {//Second loop through file fills array
        data[i] = input;
        i++;
    }
    f.close();

    for (int i = 0; i < nItems; i++) {
        sum += data[i];
    }

    cout << "The average is " << sum / nItems << ".\n"; 

    cout << endl; 
    system("pause"); 
    return 0; 
}