首页 > 解决方案 > 通过从文件中读取值来计算移动平均值

问题描述

我试图通过从文件中读取值来计算简单的 MA。

这些值的存储方式如下:

11
12
13
14
15
16
17

到目前为止,我已经这样做了:

for (int i = 0; (ifs); i++) {

        ifs >> price;
        //cout << "price:" << price;
        prices_vec.push_back(price);
        sum += prices_vec[i];
        cnt++;
        if (cnt >= 5) {

            output_file << sum / 5 << endl;
            cout << "Your SMA: " << (sum / 5) << endl;
            sum -= prices_vec[cnt - 5];
        }
    }

这有效,但最后,它最后增加了两个额外的数字。文件中的输出为:

13
14
15
15.8
0

知道为什么会发生这种情况吗?而且,有没有更有效的方法来计算 SMA?

标签: c++c++11

解决方案


我相信这会解决你的问题:

int main()
{
    int cnt = 0, sum = 0;
    vector<float> prices_vec;   
    std::ifstream ifs ("Nos.txt", std::ifstream::in); 
    float price;

    for (int i = 0; (ifs) >> price; i++) {
        prices_vec.push_back(price);
        sum += prices_vec[i];
        cnt++;
        if (cnt >= 5) {

            cout << sum / 5 << endl;
            cout << "Your SMA: " << (sum / 5) << endl;
            sum -= prices_vec[cnt - 5];
        }
    }    
    return 0;
}

推荐阅读