通过从文件中读取值来计算移动平均值

时间:2018-09-11 11:35:20

标签: c++ c++11

我正在尝试通过从文件中读取值来计算简单均线。

值的存储方式如下:

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?

1 个答案:

答案 0 :(得分:0)

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

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