/* * sample-header.c: the definitions behind sample-header.h. * Free sample from 99helpers.com/file-types/h * * Compiled once, then linked into each program that includes the header: * cc -Wall -Wextra -std=c17 -c sample-header.c (makes sample-header.o) */ /* Including its own header first lets the compiler check that every * definition below matches its declaration. Quotes, not angle brackets: * search next to this file before the system folders. */ #include "sample-header.h" /* The one definition of the variable that the header declares extern. */ const char stats_library_name[] = "99helpers sample stats " STATS_VERSION; void stats_init(stats_t *s) { s->count = 0; } bool stats_add(stats_t *s, double value) { if (s->count >= STATS_MAX_VALUES) { return false; } s->values[s->count++] = value; return true; } double stats_mean(const stats_t *s) { double sum = 0.0; for (size_t i = 0; i < s->count; i++) { sum += s->values[i]; } return s->count > 0 ? sum / (double)s->count : 0.0; } double stats_min(const stats_t *s) { double min = s->count > 0 ? s->values[0] : 0.0; for (size_t i = 1; i < s->count; i++) { if (s->values[i] < min) { min = s->values[i]; } } return min; } double stats_max(const stats_t *s) { double max = s->count > 0 ? s->values[0] : 0.0; for (size_t i = 1; i < s->count; i++) { if (s->values[i] > max) { max = s->values[i]; } } return max; }