JirR02 e5548947e2 Exercise 9
Added Exercise 9 to repository
2025-04-21 23:47:45 +02:00
..
2025-04-21 23:47:45 +02:00

Task 3: Averager

Task

Write a class Averager that computes averages of given values of type double.

Initially, an instance of class Averager does not contain any value. The class Averager must provide the following functionality:

// POST: Adds a value to the current average calculation.
void add_value(double value);

// POST: Returns the average of all added values,
//       or zero, if no value has been added.
double get_average();

// POST: Removes all values from the current average calculation.
void reset();

The declaration and implementation of class Averager must be split between header file (averager.h, containing declaration) and implementation file (averager.cpp, containing implementation).

Note: The above functions have already been declared in averager.h for you. You only need to provide function definitions in averager.cpp.

Solution

#include "averager.h"

void Averager::add_value(double value) {
  sum += value;
  ++count;
}

double Averager::get_average() {
  double res;
  if (count == 0)
    res = 0;
  else
  res = sum / count;
  return res;
}

void Averager::reset() {
  sum = 0;
  count = 0;
}

Made by JirR02 in Switzerland 🇨🇭