【问题标题】:How to get the average from data.txt file with C++?如何使用 C++ 从 data.txt 文件中获取平均值?
【发布时间】:2019-03-03 04:56:32
【问题描述】:

我们的教授希望我们修复计算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 并使用它来找到平均值,我似乎无法弄清楚。

【问题讨论】:

  • 该程序通过访问未初始化的变量sum 表现出未定义的行为。我们将在何处以及如何初始化以及将其初始化为什么值的问题留给读者作为练习。
  • 指令中提到了vector&lt;double&gt;,但这段代码中没有vector

标签: c++ file vector average


【解决方案1】:

您使用 data 进行汇总时尚未为其分配任何内存,这会导致未定义的行为。您已将值存储在 data2 中。删除不需要的变量。另外,using namespace stdis 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";
}

【讨论】:

    【解决方案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; 
    }
    

    【讨论】:

    • "看起来你没有从 txt 文件中读取数字" - 是的,他是。但他也从文件中读取项目计数,这可能正确也可能不正确,因为我们不知道文件的实际外观。 “在这里,我查看输入文件一次只是为了计算有多少数字,以便我可以制作数组。然后我再次查看它以填充数组。” - 你不需要关闭并重新打开文件,您可以将流返回到文件的开头。但是,无论如何,说明清楚地说明使用vector&lt;double&gt; 而不是double[]
    猜你喜欢
    • 2014-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    相关资源
    最近更新 更多