For a list of test scores, print the mean, the median (sort with qsort) and the population standard deviation (sqrt).
Solution
main.c
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
static int cmp(const void *a, const void *b) {
double x = *(const double *) a, y = *(const double *) b;
return (x > y) - (x < y);
}
int main(void) {
double s[] = {72, 95, 61, 88, 79, 84};
size_t n = sizeof s / sizeof s[0];
double sum = 0;
for (size_t i = 0; i < n; i++)
sum += s[i];
double mean = sum / n;
qsort(s, n, sizeof s[0], cmp);
double median = n % 2 ? s[n / 2] : (s[n / 2 - 1] + s[n / 2]) / 2;
double var = 0;
for (size_t i = 0; i < n; i++)
var += pow(s[i] - mean, 2);
printf("mean %.2f, median %.1f, std dev %.2f\n", mean, median, sqrt(var / n));
return 0;
}
Output Verified by compiling and running
mean 79.83, median 81.5, std dev 11.04
The median needs sorted data: with an even count it is the average of the two middle values. The standard deviation is the square root of the mean squared distance from the mean.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!