Skip to content

Commit

Permalink
Fix smuos#2: Add a function median()
Browse files Browse the repository at this point in the history
  • Loading branch information
zekewang918 committed Sep 27, 2014
1 parent 1d052eb commit 613ca47
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 0 deletions.
Binary file modified mm
Binary file not shown.
9 changes: 9 additions & 0 deletions mm.c
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ float mean(int *num, int length) {
return sum/length;
}

float median(int *num, int length){
if(length%2==0){
return (num[length/2-1]+num[length/2])/(float)2;
}else{
return num[length/2+1];
}
}

int main(int argc, char *argv[]) {

int i, length, *pt;
Expand Down Expand Up @@ -57,6 +65,7 @@ int main(int argc, char *argv[]) {
}

fprintf(stdout, "\nMean: %f", mean(pt, length));
fprintf(stdout, "\nMedian: %f", median(pt, length));
fprintf(stdout, "\n%s: FIN. \n", argv[0]);

return 0;
Expand Down
73 changes: 73 additions & 0 deletions mm.c~
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
#include <stdlib.h>
#include <stdio.h>

#define debug 0

// Comparison function for qsort()
int numcmp (const void *a, const void *b) {
int x = *((int*) a);
int y = *((int*) b);
if (x > y) return 1;
if (x < y) return -1;
return 0;
}

float mean(int *num, int length) {
float sum = 0;
int i;
for(i=0; i<length;i++){
sum += num[i];
}
return sum/length;
}

float median(int *num, int length){
if(length%2==0){
return (num[length/2]+num[length/2+1])/(float)2;
}else{
return num[length/2+1];
}
}

int main(int argc, char *argv[]) {

int i, length, *pt;

// Check for proper usage
if (argc < 2) {
fprintf(stderr, "%s: Aborting, not enough arguments.\n", argv[0]);
return (-1);
}

// Determine amount of numbers from argc
length = argc - 1;
#if debug
fprintf(stderr, "%s: DEBUG: %d numbers were passed.\n", argv[0], length);
#endif

// Allocate memory for array of number (and error check)
if ((pt = malloc(length * sizeof(int))) == NULL) {
fprintf(stderr, "%s: Could not allocate memory.\n", argv[0]);
}

// Read numbers into array
for (i = 0; i < length; i++) {
pt[i] = (int) strtol(argv[i+1], NULL, 10);
}

// Sort numbers
qsort(pt, length, sizeof(int), numcmp);

// Print out numbers
fprintf(stdout, "%s: Sorted output is: \n", argv[0]);
for (i=0; i<length; i++) {
fprintf(stdout, "%d ", pt[i]);
}

fprintf(stdout, "\nMean: %f", mean(pt, length));
fprintf(stdout, "\nMedian: %f", median(pt, length));
fprintf(stdout, "\n%s: FIN. \n", argv[0]);

return 0;

}

0 comments on commit 613ca47

Please sign in to comment.