I created a simple C ++ class.
#include <iostream>
using namespace std;
class Average {
public:
Average(const double initVal=0.0){accumVal=initVal;}
double getAverage(const double newVal) {
accumVal += newVal;
return accumVal / ++numAccumVal;
}
void clear(const double clearedVal=0.0) {
accumVal = clearedVal;
numAccumVal = 0;
}
private:
double accumVal;
unsigned int numAccumVal=0;
};
int main(int argc, const char * argv[]) {
Average avg;
for (size_t i=1; i<=5; ++i) {
double result = avg.getAverage(i);
cout << "Result : " << result << endl;
}
return 0;
}
And if you run the code, you will get the result as shown below.
Result : 1
Result : 1.5
Result : 2
Result : 2.5
Result : 3
Program ended with exit code: 0
source
share