计算 C++ 文件中的平均数

Counting the average numbers from a file in C++

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

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

您不能将字符串添加到 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