49 lines
1 KiB
C
49 lines
1 KiB
C
#include <stddef.h>
|
|
#include <stdint.h>
|
|
#include <stdio.h>
|
|
|
|
#include "cmaybe.h"
|
|
|
|
MAYBE_TYPE(intmax_t, intmax_t);
|
|
|
|
MAYBE(intmax_t) average(intmax_t numbers[], size_t length) {
|
|
ENABLE_RETURN(intmax_t);
|
|
if (length == 0)
|
|
RETURN_NOTHING();
|
|
|
|
intmax_t sum = 0;
|
|
for (size_t i = 0; i < length; i++) {
|
|
intmax_t num = numbers[i];
|
|
if (num > 0 && INTMAX_MAX - num < sum) {
|
|
RETURN_NOTHING();
|
|
} else if (num < 0 && INTMAX_MIN - num > sum) {
|
|
RETURN_NOTHING();
|
|
} else {
|
|
sum += num;
|
|
}
|
|
}
|
|
|
|
RETURN_VALUE(sum/length);
|
|
}
|
|
|
|
int main(void) {
|
|
intmax_t numbers[] = {5, 7, 1, -8, INTMAX_MAX};
|
|
MAYBE(intmax_t) results[6];
|
|
results[0] = average(numbers, 0);
|
|
results[1] = average(numbers, 1);
|
|
results[2] = average(numbers, 2);
|
|
results[3] = average(numbers, 3);
|
|
results[4] = average(numbers, 4);
|
|
results[5] = average(numbers, 5);
|
|
|
|
for (size_t i = 0; i < sizeof(results) / sizeof(MAYBE(intmax_t)); i++) {
|
|
IS_VALUE(results[i]) {
|
|
printf("%zu: %jd\n", i, VALUE(results[i]));
|
|
} else {
|
|
printf("%zu: No value\n", i);
|
|
}
|
|
}
|
|
|
|
return 0;
|
|
}
|