Question 2
Back to Exercise
Write range(n, ...) that finds the smallest and largest of n double values and returns them through pointer parameters placed before the ellipsis.
Solution
#include <stdarg.h>
#include <stdio.h>
void range(double *lo, double *hi, int n, ...) {
va_list ap;
va_start(ap, n);
*lo = *hi = va_arg(ap, double);
for (int i = 1; i < n; i++) {
double v = va_arg(ap, double);
if (v < *lo) *lo = v;
if (v > *hi) *hi = v;
}
va_end(ap);
}
int main(void) {
double lo, hi;
range(&lo, &hi, 5, 36.6, 39.1, 35.9, 37.2, 38.0);
printf("min %.1f, max %.1f, spread %.1f\n", lo, hi, hi - lo);
return 0;
}
min 35.9, max 39.1, spread 3.2
All values are written as double literals (36.6, not 36), because the function reads them with va_arg(ap, double).
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!