c++ - 通过从文件中读取值来计算移动平均值
问题描述
我试图通过从文件中读取值来计算简单的 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?
解决方案
我相信这会解决你的问题:
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;
}
推荐阅读
- python-3.x - 通过在 Python Pandas 中组合具有相同索引的值来创建一个新列?
- github - 从多台计算机开发的最佳方式?
- python - 使用 https 时从公共 IP 拒绝 AWS 连接
- python - 用beautifulsoup从div中提取属性值
- amazon-web-services - AWS SAM 模板:通过 AWS::Serverless::Api 创建代理
- json - MONGODB 制作愿望清单需要多少个模型?
- asp.net-core - 如何在 AspNetCore 3.1 中排除端点需要身份验证/授权?
- bash - 用 sed 替换 .py 文件中的值失败 - BASH
- lotus-notes - 在 Notes 经典 Web UI 中启用某种 Notes 嵌入视图
- asp.net - 导出 Web 部件功能不会创建 .WebPart 文件