【问题标题】:calculating moving average by reading values from a file通过从文件中读取值来计算移动平均值
【发布时间】:2018-09-11 11:35:20
【问题描述】:

我正在尝试通过从文件中读取值来计算简单 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?

【问题讨论】:

  • 顺便说一句:for (int i = 0; (ifs); i++) 中的(ifs) 的目的是什么?问题很可能出在那里
  • 您不检查ifs &gt;&gt; price; 是否有效,将此语句移动到for 条件中。所以for (int i = 0; (ifs); i++) 应该是for (int i = 0; ifs &gt;&gt; price; i++)
  • 我的意思是,如果您使用std::vector,您将创建第一个函数来从流中创建它。 (然后您可以检查矢量内容是否符合您的预期)。然后是计算移动平均线的第二个函数。 (您可以独立于文件/流进行测试,因为您只需要一个 std::vector)。

标签: c++ c++11


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多