【问题标题】:Counting the average numbers from a file in C++在 C++ 中计算文件的平均数
【发布时间】:2020-04-29 08:38:02
【问题描述】:

我必须计算保存在文件中的数字的平均值,但出现“+”运算符错误。有什么问题?

int main()
{
    int a;
    fstream File;
    string Line;
    File.open("file.txt", ios::in);
    if (File.is_open()){
    while(!File.eof()) //.eof -> End Of File
    {
        File>>Line;
        a=a+Line;
        cout<<Line<<"\n";
        cout << a;
    }
    }
    else{
        cout << "File open error";
    }
    File.close();
    return 0;
}

【问题讨论】:

标签: c++ file average


【解决方案1】:

您不能将字符串添加到 int。读入一个 int 开始,而不是读入一个字符串。

您也根本没有计算平均值,就像您的问题所要求的那样。你只是在计算一个总和。

试试这个:

int main() {
    ifstream File("file.txt");
    if (File.is_open()) {
        int num, count = 0, sum = 0;
        while (File >> num) {
            ++count;
            sum += num;
        }
        if (File.eof()) {
            cout << "count: " << count << endl;
            cout << "sum: " << sum << endl;
            if (count != 0) {
                int average = sum / count;
                cout << "average: " << average << endl;
            }
        }
        else {
            cerr << "File read error" << endl;
        }
    }
    else {
        cerr << "File open error" << endl;
    }
    return 0;
}

Live Demo

【讨论】:

  • 感谢您的回答,但我收到错误:文件读取错误。
  • 我的文件只包含单个数字,例如。 12.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-08
  • 2021-02-02
  • 2019-04-08
  • 1970-01-01
  • 2018-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多