Skip to content

Commit

Permalink
fixed smuos#2 which is add a function, mean(), to mm.c to calculate t…
Browse files Browse the repository at this point in the history
…he mean
  • Loading branch information
Yumingz committed Sep 29, 2014
1 parent 420a303 commit 70c0f7e
Showing 1 changed file with 70 additions and 0 deletions.
70 changes: 70 additions & 0 deletions mm.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
#include <stdlib.h>
#include <stdio.h>

#define debug 0


//Declare variables
double sum=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;
}

// Find mean
double mean(int* num, int size) {
// Read all numbers
int i;
for (i=0; i<=size-1; i++) {
//add all numbers
sum += num[i];
}
// Calculate meas
int mean = sum / size;
return mean;
}

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]);
return -1;
}

// 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, "\n%s: FIN. \n", argv[0]);

return 0;
}

0 comments on commit 70c0f7e

Please sign in to comment.