【问题标题】:Read a .txt file, calculate sum and mean读取 .txt 文件,计算总和和均值
【发布时间】:2016-01-19 18:30:08
【问题描述】:

我有一个包含数字的 .txt 文件,如下所示:

1
2
3

数字并不重要,但它们都从新行开始。

然后我想在文本文件中找到数字的总和和平均值。

这是我目前所拥有的:

#include<cmath>
#include<cstdlib>
#include<iomanip>
#include<string>
#include<fstream>
using namespace std;

int main(int argc, char * argv[])
{
    std::fstream myfile("numbers.txt", std::ios_base::in);

    float a;
    while (myfile >> a)
    {
        printf("%f ", a);
    }

    getchar();

    return 0;

int sum(0);
int sumcount(0);
double average(0);
int even(0);
int odd(0);

ifstream fin;

string file_name;

int x(0);

cout<<"numbers.txt";
cin>> file_name;
fin.open(file_name.c_str(),ios::in);

if (!fin.is_open())
{
    cerr<<"Unable to open file "<<file_name<<endl;
    exit(10);

}

fin>>x;
    while (!fin.fail())
    {
        cout<<"Read integer: "<<x<<endl;
        fin>>x;
        sum=sum+x;
        sumcount++;
        if(x%2==0)
            even++;
        else
            odd++;

    }

    fin.close();
    average=(double)sum/sumcount;
    cout<<"Sum of integers: "<<sum<<endl;
    cout<<"Average: "<<average<<endl;
    cout<<"Number of even integers: "<<even<<endl;
    cout<<"Number of odd integers: "<<odd<<endl;

    return 0;
}

开始加载数字,但不会执行下一步。

我查看了很多其他代码并尝试实现其他想法来解决问题;但是,有些人使用循环和数组以及其他东西,我不确定该使用哪个。

如何让我的程序找到文件中数字的总和和平均值?

还有任何其他的帮助链接将不胜感激

编辑:虽然数字是整数,但平均值可能不是

【问题讨论】:

  • while (!fin.fail()) =>while (fin &gt;&gt; x) 对于初学者。
  • 提示#1:在main() 几乎开头的无条件return 0; 通常是个坏主意,您的程序将不会在该行之后继续。

标签: c++ sum average mean


【解决方案1】:
#include <iostream>
#include <fstream>
using namespace std;


int main() {

int n=0;
int sum=0,total=0;

fstream file("numbers.txt");
while(file >> n) // or while(cin >> n) to read from stdin, commandline
{
    sum += n;
    total++;
}

int average = (float) sum/total;

cout<<"sum: " << sum << endl;
cout << "average: " << average << endl;
return 0;
}

【讨论】:

    【解决方案2】:

    一旦你的 main 函数遇到 return 0 语句,它将退出程序并且无法执行剩余的代码。这通常应该只在你的主函数中出现一次,在你的代码块的末尾

    【讨论】:

      【解决方案3】:

      这是您的工作代码。

      #include <cmath>
      #include <cstdlib>
      #include <iostream>
      #include <iomanip>
      #include <string>
      #include <fstream>
      
      
      using namespace std;
      
      int main(int argc, char * argv[])
      {
          std::fstream myfile("numbers.txt", std::ios_base::in);
      
          float a = 0;
      
          myfile >> a;
      
          while (!myfile.fail())
          {
              printf("%f ", a);
              myfile >> a; // here you dispay your numbers
          }
      
          getchar(); // waiting for input
      
          float sum(0);
          int x(0);
          int sumcount(0);
          double average(0);
          int even(0);
          int odd(0);
      
          ifstream fin;
      
          string file_name;
      
          cout<<"numbers.txt" << endl;
      
          cin>> file_name; // waiting for enter file name
      
          fin.open(file_name.c_str(),ios::in);
      
          if (!fin.is_open())
          {
              cerr<<"Unable to open file "<<file_name<<endl;
              exit(10);
          }
      
          fin >> x;
      
          while (!fin.fail())
          {
              cout<<"Read integer: "<<x<<endl; // display number again
      
              sum=sum+x;
              sumcount++;
              if(x % 2==0)  // compuing your file statistics
                  even++;
              else
                  odd++;
      
              fin>>x;
          }
      
          fin.close();
          average=(double)sum/sumcount;
      
          cout<<"Sum of integers: "<<sum<<endl; // displaying results
          cout<<"Average: "<<average<<endl;
          cout<<"Number of even integers: "<<even<<endl;
          cout<<"Number of odd integers: "<<odd<<endl;
      
          return 0;
      }
      

      我添加了一些最小的改动以使您的程序正常运行。

      结果

      还有更多

      【讨论】:

      • 谢谢 - 我正在使用 xcode,我的输出只是给了我文件中的数字,而不是总和或平均值 - 你知道为什么吗?
      • 程序显示数字后尝试回车
      • 它只返回文件 numbers.txt 的名称
      • 然后输入“number.txt”
      • 而且你必须知道你的代码在做什么,很明显你不明白你的程序在做什么。
      【解决方案4】:
      #include <iostream>
      #include<fstream>
      
      int main()
      {
          std::ifstream txtFile;
          txtFile.open("data.txt");
          //TODO: check if the file fails to open.
      
          double tempNum, mean(0.0), sum(0.0), count(0.0);
          while (txtFile >> tempNum)
          {
              sum += tempNum;
              ++count;
          }
          mean = sum/count;
          std::cout << "mean: " << mean << "  sum: " << sum << std::endl;
      
          return 0;
      }
      

      【讨论】:

      • 我没有看到所有答案。
      猜你喜欢
      • 2014-01-24
      • 1970-01-01
      • 2018-09-26
      • 1970-01-01
      • 2019-01-18
      • 1970-01-01
      • 2015-06-04
      • 1970-01-01
      • 2015-12-06
      相关资源
      最近更新 更多