I'm trying to calculate simple MA by reading values from a file.
The values are stored like this:
11
12
13
14
15
16
17
I've did this so far:
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];
}
}
This works, but at the end, it adds two additional numbers in the end. The output in file is:
13
14
15
15.8
0
Any idea why this might be happening? And, is there a more efficient way to calculate SMA?