Exercise 9

Added Exercise 9 to repository
This commit is contained in:
2025-04-21 23:47:45 +02:00
parent 950098d35e
commit e5548947e2
4 changed files with 444 additions and 0 deletions

View File

@@ -0,0 +1,62 @@
#+title: Task 3: Averager
#+author: JirR02
* Task
:PROPERTIES:
:CUSTOM_ID: task
:END:
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:
#+begin_src cpp
// 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();
#+end_src
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
:PROPERTIES:
:CUSTOM_ID: solution
:END:
#+begin_src cpp
#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;
}
#+end_src
--------------
Made by JirR02 in Switzerland 🇨🇭