UPDATED: I am writing a program that finds the moving average and I cannot seem to figure out why my code does not work. It gets the correct numbers but does not format correctly. For example, my program outputs "34" instead of "34.00" and I thought that making the variable type 'double' would fix this.
Prompt for the program: Write a program that outputs a moving average (see: https://en.wikipedia.org/wiki/Moving_average) For a series of whitespace delimited integers (note, the running average should be rounded to the hundredth place. However, if a non-positive number is encountered, the average should be reset and a newline character emitted. Otherwise, the running averages should be separated by a space.
When a '0' or a negative number is inputted, the program is supposed to skip that number and reset the count to 0 and continue looping for any positive numbers inputted after that.
Input: 34 99 12 19 44
Expected Output: 34.00 66.50 48.33 41.00 41.60
My Output: 34 66.5 48.3333 41 41.6
My Code:
#include <iostream>
using std::cin; using std::cout; using std::endl;
double input;
double count = 0;
double sum;
double avg;
double prev = 0;
int main(){
while (cin >> input){
if (input == 0 || input < 0)
count = 0;
else
count++;
sum = input + prev;
prev = sum;
avg = sum / count;
cout << avg << ' ';
}
}