Как получить среднее значение из файла data.txt с помощью C ++? - PullRequest
0 голосов
/ 03 марта 2019

Наш профессор хочет, чтобы мы исправили код, который подсчитывает количество значений в файле 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;
}

Его инструкции были:

Изменить код, который работал сегодня, чтобы среднее значение данных в векторных данных вычислялось правильно.Прямо сейчас код просто дает вам значение, которое не является средним.

Я пытался изменить переменную nItems на 12, и это, похоже, сработало, но цель кода - определитьnItems и используйте это, чтобы найти среднее значение, которое я не могу понять.

Ответы [ 2 ]

0 голосов
/ 03 марта 2019

Вы используете data, для которого не было выделено никакой памяти при суммировании. Это вызывает неопределенное поведение.Вы сохранили свои значения в data2.Удалите переменные, которые вам не нужны.Также, using namespace std считается плохой практикой .

#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";
}
0 голосов
/ 03 марта 2019

Эй, похоже, вы не читали цифры из текстового файла.Здесь я просматриваю входной файл один раз, чтобы подсчитать, сколько чисел существует, чтобы я мог создать массив.Затем я просматриваю его снова, чтобы заполнить массив.

#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; 
}
...